<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class TiApply2 extends Commonti
{
     public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        $fid=2;$aid=$data["aid"];
        
            $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
            //print_r($res);exit;
            if($res["operateStatus"]=="success"){
                $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=1")->field("yd.id")->select();
                if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                        $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                }
                    try{
                        $up["id"]=$aid;
                        $up["status"]=8;
                        Db::table("cg_ti")->update($up);
                    }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
                     
                }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
      
        
    }
	//列表
    public function index($page=1,$list=20)
    {

        $request = Request::instance();


        $data = $request->post();
        $eid=Session::get("employee_id");
        $where = "t.type_id=0 and t.cuser=$eid ";
        if ($data) {
            if ($data["no"])
                $where .= "and t.sn={$data["no"]} ";
            if (trim($data["title"]))
                $where .= "and t.title like '%{$data["title"]}%' ";
            if ($data["status"])
                $where .= "and t.status={$data["status"]} ";
            if (trim($data["start"])) {
                $st = strtotime($data["start"]);
                $where .= "and t.ctime>=$st ";
            }
            if (trim($data["end"])) {
                $ed = strtotime($data["end"]) + 24 * 3600;
                $where .= "and t.ctime<$ed ";
            }
        } else {
            $data = ["no" => "", "title" => "", "status" => "", "start" => "", "end" => ""];
        }
        $sum= Db::table('cg_ti t')->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $applys = Db::table('cg_ti t')->order("t.id desc")->where($where)->limit($start,$list)->select();


        foreach($applys  as $k=>$v){
            $v['cusername'] = Db::table('employee')->where(array('id'=>$v['cuser']))->value('em_name');
            $v['pusername'] = Db::table('employee')->where(array('id'=>$v['puser']))->value('em_name');
            $v['cate_title'] = Db::table('cg_ti_cate')->where(array('id'=>$v['cate_id']))->value('title');
            $v['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $v['ptime'] = date('Y-m-d H:i',$v['ptime']);
            switch ($v['status']){
                case 2:
                    $v['status_title'] = '已打回';
                    break;
                case 3:
                    $v['status_title'] = '区域领导审批';
                    break;
                case 4:
                    $v['status_title'] = '拆分人审批';
                    break;
                case 5:
                    $v['status_title'] = '集团领导审批';
                    break;
                case 6:
                    $v['status_title'] = '抄送';
                    break;
                case 7:
                    $v['status_title'] = '已归档';
                    break;
                case 8:
                    $v['status_title'] = '已作废';
                    break;
                case 9:
                    $v['status_title'] = '已否决';
                    break;
                default:
                    $v['status_title'] = '草稿';
            }

            //反馈完成之后才能显示核销按钮
            $v['fb_status'] = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$v['id']])->value('state');

            //查询状态在审核中的核销单是否存在
            $tiids = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')->where(['t.status'=>1,'ti_id'=>$v['id']])->column('t2.ti_id');
            $tiids = array_unique($tiids);
            $v['hx_status'] = in_array($v['id'],$tiids)?true:false;

            //查询状态在审核通过的核销单是否存在
            $tiids = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')->where(['t.status'=>2,'ti_id'=>$v['id']])->column('t2.ti_id');
            $tiids = array_unique($tiids);
            $v['yhx'] = in_array($v['id'],$tiids)?true:false;


            $applys[$k] = $v;
        }

         $this->assign("applys", $applys);

        $this->assign("data", $data);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);

        return $this->fetch();
    }
    public function baocunchuli(){
        $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');
            
            $ti_id = $this->request->post('ti_id');
            $aid=$ti_id;
            if (!$validate->check($data)) {
                return json_encode(["msg" => $validate->getError(), "state" => 2]);
            }
            $list = $this->request->post('list');
            if(!$list){
                return json_encode(["msg" => "至少添加一条费用明细", "state" => 2]);
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }

            //$savetype = $this->request->post('savetype');
           // echo json_encode(["msg" => $savetype, 'success'=>false]);die;
                 //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$ti_id]);
                }

                db("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui,yjsjtrfy=hanshui where ti_id=$ti_id");
                $data['status'] = 3;//提交工作流
               
                Db::startTrans();
            try {
                $ys=$this->tiys($aid);$data["id"]=$aid;
                    if($ys===0&&$dataup["status"]==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                $res1 = Db::table("cg_ti")->update($data);

               
                
                if($ys){
                    Db::table("yusuan_detail")->insertAll($ys);
                }
                    
               

            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => $e->getMessage(), "state" => 2]);
            }
            if ($res1) {
                $fid=2;
                $res=$this->goworker($fid,$aid,$this->request->post('nodeKey'),$this->request->post('selectId'),$this->request->post('selectName'));
                if($res["operateStatus"]=="success"){
                                Db::commit();
                                return json_encode(["msg"=>"","state"=>1]);
                            }else{
                                Db::rollBack();
                                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                            }
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
       
    

    }
    public function add(){

        $from=1;
        $this->assign("from",$from);
       // $data["status"]=0;
        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');
            
            $ti_id = $this->request->post('ti_id');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }

            $savetype = $this->request->post('savetype');
           // echo json_encode(["msg" => $savetype, 'success'=>false]);die;
                 //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$ti_id]);
                }
            if($savetype=='save2'){
                db("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui,yjsjtrfy=hanshui where ti_id=$ti_id");
                $data['status'] = 3;//提交工作流
                $ys=$this->tiys($ti_id);
                if($ys===0){
                    echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
                }
                if($ys){
                    db("yusuan_detail")->insertAll($ys);
                }
                $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');

                $data2 = [];
                $data2['accessToken'] = session('accessToken');
                $data2['flowId'] = $flowId;
                $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data2);
                $insert = [];
                $insert['ywlx'] = 2;
                $row = db('cg_ti')->where('id',$ti_id)->field('title,sn')->find();
                $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
                $insert['yw_id'] = $ti_id;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
                $insert['sqr_id'] = session('employee_id');
                $insert['workId'] = $data2->workId;
                $insert['trackId'] = $data2->flowNode->trackId;
                db('cg_workflow')->insert($insert);
            }

            $bool = Db::table('cg_ti')->where('id',$ti_id)->update($data);
            if(false !== $bool){

                //更新附件表
                if(isset($attachids)){

                    Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$ti_id,'target_table'=>'cg_ti'));

                }

               

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"添加成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"添加失败"
                ]);die;
            }

        }
       // $this->assign("data",$data);
        $this->template();
        return $this->fetch('form');
    }

    //添加数据
    public function addData(){

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        return $this->fetch();
    }

    //修改数据行
    public function updateData(){
        $id = $this->request->get('id');

        if($_POST){

            $validate = new Valid([
                'start|促销执行时间'  => 'require|dateFormat:Y-m-d',
                'end|促销执行时间'  => 'require|dateFormat:Y-m-d|gt:start',
                'head|负责人'  => 'require',
                'expCanTime|预计核销时间'  => 'require|dateFormat:Y-m-d',
                'totalExpectedSales|总预计销量'  => 'require',
                'totalBenchmarkSales|总基准销量'  => 'require',
                'feetype|费用类型'  => 'require',
                'amount|未税总额'  => 'require',
                'paymethod|费用支付方式'  => 'require',
                'jrbm|费用计入部门'  => 'require',
                'project|费用计入方案'  => 'require',
            ]);

            $data = [];
            $data['net_id'] = $this->request->post('net_id');
            $data['start'] = $this->request->post('start');
            $data['end'] = $this->request->post('end');
            $data['head'] = $this->request->post('head');
            $data['expCanTime'] = $this->request->post('yjverifyTime');
            $data['totalExpectedSales'] = $this->request->post('totalExpectedSales');
            $data['totalBenchmarkSales'] = $this->request->post('totalBenchmarkSales');
            $data['feetype'] = $this->request->post('feetype');
            $data['amount'] = $this->request->post('amount');
            $data['paymethod'] = $this->request->post('paymethod');
            $data['buhuo'] = $this->request->post('buhuo');
            $data['jrbm'] = $this->request->post('jrbm');
            $data['project'] = $this->request->post('project');
            $data['brief'] = trim($this->request->post('brief'));

            $arealat= trim($this->request->post('arealat'));
            switch ($arealat){
                case 2:
                    $data['net_id'] = $this->request->post('net_id');
                    if(!$data['net_id']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择网点"
                        ]);die;
                    }
                    break;
                

            }
            $productlat= trim($this->request->post('productlat'));
            switch ($productlat){
                case 1:
                    $data['brand'] = $this->request->post('brand');
                    if(!$data['brand']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择品牌"
                        ]);die;
                    }
                    break;
                case 2:
                    $data['category'] = $this->request->post('category');
                    if(!$data['category']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择品类"
                        ]);die;
                    }
                    break;
                case 3:
                    $data['series'] = $this->request->post('series');
                    if(!$data['series']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择系列"
                        ]);die;
                    }
                    break;
                case 4:
                    $data['sku'] = $this->request->post('sku');
                    if(!$data['sku']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择sku"
                        ]);die;
                    }
                    break;
                default:
                    $data['product'] = $this->request->post('product');
                    if(!$data['product']){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"请选择单品"
                        ]);die;
                    }
            }

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $data['expCanTime'] = strtotime($data['expCanTime']);
            $data['start'] = strtotime($data['start']);
            $data['end'] = strtotime($data['end']);

            //修改其他
            $bool = Db::table('cg_ti_list')->where('id',$id)->update($data);
            if(false !== $bool){
//                echo db('cg_ti_list')->getLastSql();
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
        }

        $this->template();

        //查询非常规促销明细
        if($id){
            $list = db('cg_ti_list')->where('id',$id)->find();
            $list['jxs_title'] = db('cg_jxs')->where('id',$list['jxs_id'])->value('title');
            $list['net_title'] = db('cg_net')->where('id',$list['net_id'])->value('title');
            $list['brand_title'] = db('pro_brands')->where('id',$list['brand'])->value('brand_name');
            $list['category_title'] = db('pro_category')->where('id',$list['category'])->value('category_name');
            $list['series_title'] = db('pro_series')->where('id',$list['series'])->value('series_name');
            $list['sku_title'] = db('pro_sku')->where('id',$list['sku'])->value('sku_name');
            $list['product_title'] = db('pro_products')->where('id',$list['product'])->value('pro_name');
            $list['feetype_title'] = db('cg_feiyongkemu3')->where('id',$list['feetype'])->value('title');
            $list['jrbm_title'] = db('cg_fijiruzd')->where('id',$list['jrbm'])->value('title');
            if($list['payee']==1){
                $list['gys_name'] = db('gys')->where('id',$list['gys'])->value('gys_name');
            }
            $ti = db('cg_ti')->where('id',$list['ti_id'])->field('arealat,productlat')->find();
            $list = array_merge($list,$ti);
            //print_r($list);
            $this->assign('list',$list);
        }

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        return $this->fetch();
    }

    //添加费用项目行
    public function addFeiyong(){
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fijiru = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fijiru);

        $str = '';
        foreach($fipay as $k=>$v){
            $str .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
        $str2 = '';
        foreach($fijiru as $k=>$v){
            $str2 .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }

        $name = 'a'.mt_rand();
        echo <<<EOF
<tr class="data">
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control feetype" name="feetype" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary feetree" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <input type="radio" name="{$name}" value="0" class="payee" checked>经销商&nbsp;
                    <input type="radio" name="{$name}" value="1" class="payee" disabled>供应商

                </td>
                <td><input type="text" name="amount" class="form-control"></td>
                <td>
                    <select name="paymethod"  class="form-control">
                        <option value="">请选择</option>
                        {$str}
                    </select>
                </td>
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control jrbm" name="jrbm" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">f111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary select_jrbm" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <select name="project" class="form-control">
                        <option value="">请选择</option>
                        {$str2}
                    </select>
                </td>
                <td class="text-center">
                    <button class="btn btn-danger del_fi_item" type="button">删除</button>
                </td>
            </tr>
EOF;

    }


    public function produceSN(){
        //生成编号
        $max = db('cg_ti')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //生成反馈sn
    public function producefbSN(){
        //生成编号
        $max = db('all_ti_feeback_list')->where('no','like',date('Ymd').'%')->max('no'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //生成反馈sn
    public function producehxSN(){
        //生成编号
        $max = db('cg_ti_hexiao')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //提交整个费用项目
    public function appendRow(){

        $ti_id = $this->request->post('ti_id');

        $list = $this->request->post('list/a');
        $start = $this->request->post('start');
        $end = $this->request->post('end');
        $yjverifyTime = $this->request->post('yjverifyTime');
        $totalExpectedSales = $this->request->post('totalExpectedSales');
        $totalBenchmarkSales = $this->request->post('totalBenchmarkSales');
        $jxs = $this->request->post('jxs');
        $jxs_id = $this->request->post('jxs_id');
        $head = $this->request->post('head');
        $brief = $this->request->post('brief');
        $net = $this->request->post('net_id/a');
        $brand = $this->request->post('brand/a');
        $category = $this->request->post('category/a');
        $series = $this->request->post('series/a');
        $sku = $this->request->post('sku/a');
        $product = $this->request->post('product/a');

        if(!$jxs_id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"请选择经销商"
            ]);die;
        }

        //保存
        $insert = [];

        //总条数
        $totalCnt = count($list);
        if($brand) {
            $totalCnt = $totalCnt * count($brand);
        }
        if($category) {
            $totalCnt = $totalCnt * count($category);
        }
        if($series) {
            $totalCnt = $totalCnt * count($series);
        }
        if($sku) {
            $totalCnt = $totalCnt * count($sku);
        }
        if($product) {
            $totalCnt = $totalCnt * count($product);
        }
        //如果选择网点
        if($net){

            $totalCnt *= count($net);
            foreach($net as $net_k=>$net_v){
                //如果选择的品牌
                if($brand){
                    foreach($brand as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['gys'] = $v['gys'];
                            $data['amount'] = round($v['amount']/$totalCnt,2);
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net_id'] = $net_v;//网点
                            $data['brand'] = $vv;//品牌
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|gt:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net_id|网点'  => 'require',
                                'brand|品牌'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择的品类
                if($category){
                    foreach($category as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['gys'] = $v['gys'];
                            $data['amount'] = round($v['amount']/$totalCnt,2);
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net_id'] = $net_v;//网点
                            $data['category'] = $vv;//品类
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量
                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net_id|网点'  => 'require',
                                'category|品类'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择系列
                if($series){
                    foreach($series as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['gys'] = $v['gys'];
                            $data['amount'] = round($v['amount']/$totalCnt,2);
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net_id'] = $net_v;//网点
                            $data['series'] = $vv;//系列
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net_id|网点'  => 'require',
                                'series|系列'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择sku
                if($sku){
                    foreach($sku as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['gys'] = $v['gys'];
                            $data['amount'] = round($v['amount']/$totalCnt,2);
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net_id'] = $net_v;//网点
                            $data['sku'] = $vv;//系列
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net_id|网点'  => 'require',
                                'sku'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }

                //如果选择单品
                if($product){
                    foreach($product as $kk=>$vv){
                        foreach($list as $k=>$v) {
                            $data = [];
                            $data['feetype'] = $v['feetype'];
                            $data['paymethod'] = $v['paymethod'];
                            if(isset($v['buhuo']))
                                $data['buhuo'] = $v['buhuo'];
                            $data['project'] = $v['project'];
                            $data['jrbm'] = $v['jrbm'];
                            $data['payee'] = $v['payee'];
                            $data['gys'] = $v['gys'];
                            $data['amount'] = round($v['amount']/$totalCnt,2);
                            $data['start'] = $start;
                            $data['end'] = $end;
                            $data['expCanTime'] = $yjverifyTime;
                            $data['jxs_id'] = $jxs;
                            $data['head'] = $head;
                            $data['brief'] = $brief;
                            $data['net_id'] = $net_v;//网点
                            $data['product'] = $vv;//单品
                            $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                            $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                            $validate = new Valid([
                                'start|促销执行时间开始时间'  => 'require',
                                'end|促销执行时间结束时间'  => 'require|>:start',
                                'head|负责人'  => 'require',
                                'expCanTime|预计核销时间'  => 'require',
                                'totalExpectedSales|总预计销量'  => 'require',
                                'totalBenchmarkSales|总基准销量'  => 'require',
                                'brief|备注'  => 'max:200',
                                'feetype|费用类型'  => 'require',
                                'payee|收款方'  => 'require',
                                'amount|未税总额'  => 'require',
                                'paymethod|费用支付方式'  => 'require',
                                'jrbm|费用计入部门'  => 'require',
                                'project|费用计入方案'  => 'require',
                                'jxs_id|经销商'  => 'require',
                                'net_id|网点'  => 'require',
                                'product|单品'  => 'require',
                            ]);

                            if (!$validate->check($data)) {
                                echo  json_encode([
                                    "success"=>false,
                                    "msg"=>$validate->getError()
                                ]);die;
                            }
                            $data['cuser'] = $_SESSION['think']['employee_id'];
                            $data['ctime'] = time();
                            $data['puser'] = $_SESSION['think']['employee_id'];
                            $data['ptime'] = time();
                            $insert[] = $data;
                        }
                    }
                }
            }
        }else{ //如果选择经销商

            //如果选择的品牌
            if($brand){
                foreach($brand as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['gys'] = $v['gys'];
                        $data['amount'] = round($v['amount']/$totalCnt,2);
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['brand'] = $vv;//品牌
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'brand|品牌'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择的品类
            if($category){
                foreach($category as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['gys'] = $v['gys'];
                        $data['amount'] = round($v['amount']/$totalCnt,2);
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['category'] = $vv;//品类
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'category|品类'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择系列
            if($series){
                foreach($series as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['gys'] = $v['gys'];
                        $data['amount'] = round($v['amount']/$totalCnt,2);
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['series'] = $vv;//系列
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'series|系列'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择sku
            if($sku){
                foreach($sku as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['gys'] = $v['gys'];
                        $data['amount'] = round($v['amount']/$totalCnt,2);
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['sku'] = $vv;//系列
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'sku'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }

            //如果选择单品
            if($product){
                foreach($product as $kk=>$vv){
                    foreach($list as $k=>$v) {
                        $data = [];
                        $data['feetype'] = $v['feetype'];
                        $data['paymethod'] = $v['paymethod'];
                        if(isset($v['buhuo']))
                            $data['buhuo'] = $v['buhuo'];
                        $data['project'] = $v['project'];
                        $data['jrbm'] = $v['jrbm'];
                        $data['payee'] = $v['payee'];
                        $data['gys'] = $v['gys'];
                        $data['amount'] = round($v['amount']/$totalCnt,2);
                        $data['start'] = $start;
                        $data['end'] = $end;
                        $data['expCanTime'] = $yjverifyTime;
                        $data['jxs_id'] = $jxs_id;
                        $data['head'] = $head;
                        $data['brief'] = $brief;
                        $data['product'] = $vv;//单品
                        $data['totalExpectedSales'] = round($totalExpectedSales/$totalCnt,2);//总预计销量
                        $data['totalBenchmarkSales'] = round($totalBenchmarkSales/$totalCnt,2);//总基准销量

                        $validate = new Valid([
                            'start|促销执行时间开始时间'  => 'require',
                            'end|促销执行时间结束时间'  => 'require|>:start',
                            'head|负责人'  => 'require',
                            'expCanTime|预计核销时间'  => 'require',
                            'totalExpectedSales|总预计销量'  => 'require',
                            'totalBenchmarkSales|总基准销量'  => 'require',
                            'brief|备注'  => 'max:200',
                            'feetype|费用类型'  => 'require',
                            'payee|收款方'  => 'require',
                            'amount|未税总额'  => 'require',
                            'paymethod|费用支付方式'  => 'require',
                            'jrbm|费用计入部门'  => 'require',
                            'project|费用计入方案'  => 'require',
                            'jxs_id|经销商'  => 'require',
                            'product|单品'  => 'require',
                        ]);

                        if (!$validate->check($data)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$validate->getError()
                            ]);die;
                        }
                        $data['cuser'] = $_SESSION['think']['employee_id'];
                        $data['ctime'] = time();
                        $data['puser'] = $_SESSION['think']['employee_id'];
                        $data['ptime'] = time();
                        $insert[] = $data;
                    }
                }
            }
        }

        //判断是否存在费用类型相同收款方也相同的情况 ---暂时待做

        //根据经销商一些信息
        $jxs_info = db('cg_jxs')->where('id',$jxs_id)->field('zoning,provice,city')->find();
        $jxs_info['zoning'] = db('cg_market_zoning')->where('id',$jxs_info['zoning'])->value('title');
        $jxs_info['provice'] = db('cg_market_provice')->where('id',$jxs_info['provice'])->value('title');
        $jxs_info['city'] = db('cg_market_city')->where('id',$jxs_info['city'])->value('title');

        //如果主表存在
        if($ti_id){
            //查询主表编号
            $insert_sn = db('cg_ti')->where('id',$ti_id)->value('sn');
            $basic = db('cg_ti_list')->where('ti_id',$ti_id)->max('sn'); //编号递增开始位置基础

        }else{ //如果主表不存在

            $insert_sn = $this->produceSN();//生成编号
            $ti_title = $this->request->post('ti_title');
            $ti_arealat = $this->request->post('ti_arealat');
            $ti_productlat = $this->request->post('ti_productlat');
            $ti_jxs_id = $this->request->post('ti_jxs_id');

            db('cg_ti')->insert([
                'sn'=>$insert_sn,
                'title'=>$ti_title,
                'arealat'=>$ti_arealat,
                'productlat'=>$ti_productlat,
                'jxs_id'=>$ti_jxs_id,
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
            ]);
            $ti_id = db('cg_ti')->getLastInsID();
            $basic = 0; //编号递增开始位置基础
        }

        $yjverifyTime1 = strtotime($yjverifyTime);
        $start1 = strtotime($start);
        $end1 = strtotime($end);

        foreach($insert as $k=>$v){
            $v['sn'] = ($basic+$k+1);
            $v['expCanTime'] = $yjverifyTime1;
            $v['start'] = $start1;
            $v['end'] = $end1;
            $v['ctime'] = time();
            $v['ptime'] = time();
            $v['cuser'] = Session::get('employee_id');
            $v['puser'] = Session::get('employee_id');
            $v['ti_id'] = $ti_id;
            $v['shuilv'] = 6; //税率
            $v['isVAT'] = 0; //是否增值税,0否，1是
            $v['hanshui'] = $v['amount']*(1+6/100); //含税费用金额
            //预计实际投入费用
            $v['yjsjtrfy'] = $v['hanshui'];
            $v['yujifeiyonglv'] = $v['hanshui']/$v['totalExpectedSales']*100; //预计费用率
            $v['2srjizhun'] = 0; //2sr基准销量

            //品牌毛利率
            if(isset($v['brand']))
                $brand = $v['brand'];
            elseif(isset($v['category']))
                $brand = findBrandByCategory($v['category']);
            elseif(isset($v['series']))
                $brand = findBrandBySeries($v['series']);
            elseif(isset($v['sku']))
                $brand = findBrandBySku($v['sku']);
            elseif(isset($v['product']))
                $brand = findBrandByProduct($v['product']);
            $brand_rate  = db('pro_brands')->where(['id'=>$brand])->value('profit');
            $brand_rate = $brand_rate/100;
//            dump($brand_rate);die;
            $v['yujiroi'] = round(($v['totalExpectedSales']-$v['totalBenchmarkSales'])*$brand_rate/$v['yjsjtrfy'],2); //预计rio
            $v['status'] = 0; //状态0，正常
            $insert[$k] = $v;
            db('cg_ti_list')->insert($v);
            $insert[$k]['id'] = db('cg_ti_list')->getLastInsID();
        }

        $data = Db::table('cg_ti')->where('id',$ti_id)->find();

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';

        //明细table
        $str = $this->feeList($ti_id,$data['arealat'],$data['arealat_title'],$data['productlat'],$data['productlat_title'],$data['jxs_id'],$data['jxs_title'],$data['sn']);

        echo  json_encode([
            "success"=>true,
            "data"=>$str,
            "ti_id"=>$ti_id,
            "jxs_info"=>$jxs_info['zoning'].'&nbsp;'.$jxs_info['provice'].'&nbsp;'.$jxs_info['city'].'&nbsp;性质：经销'
        ]);die;

    }

    //明细table

    /**
     * @param $id ti_id
     * @param $arealat 区域纬度类型
     * @param $arealat_title 区域纬度标题
     * @param $productlat 产品纬度类型
     * @param $productlat_title 产品纬度标题
     * @param $jxs_id 经销商id
     * @param $jxs_title 经销商标题
     * @param $sn ti编号
     * @return string
     */
    private function feeList($id,$arealat,$arealat_title,$productlat,$productlat_title,$jxs_id,$jxs_title,$sn){


        //查询明细列表
        if($arealat==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-实际投入费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
            }
        }

        $st_amount = db('cg_ti_list')->where(['ti_id'=>$id])->sum('amount');//总计-未税费用金额
        $st_hanshui = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $st_shijitourufeiyong = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yjsjtrfy');//总计-实际投入费用
        $st_shijitourufeiyong = round($st_shijitourufeiyong,2);
        $st_yujixiaoliang = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $st_yujixiaoliang = round($st_yujixiaoliang,2);
        $st_yujifeiyonglv = $st_hanshui/$st_yujixiaoliang*100;//总计-预计费用率
        $st_yujifeiyonglv = round($st_yujifeiyonglv,2);
        $st_2srjizhun = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $st_jizhunxiaoliang = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $st_jizhunxiaoliang = round($st_jizhunxiaoliang,2);
        $st_yujiroi = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio

        //表格标头
        $mc = "<td style=\"min-width:120px\">{$arealat_title}</td>";
        $prolat = "<td style=\"min-width:100px\">{$productlat_title}</td>";
        $str = <<<EOF
                    <thead>
            <tr class="info">
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td style="min-width:80px">序号</td>
                <td style="min-width:160px">明细编号</td>
                {$mc}
                <td style="min-width: 200px">活动执行时间</td>
                <td style="min-width: 100px">预计核销时间</td>
                {$prolat}
                <td style="min-width: 100px">三级费用科目</td>
                <td style="min-width: 100px">费用支付方式</td>
                <td style="min-width: 100px">未税费用金额</td>
                <td style="min-width: 100px">税率</td>
                <td style="min-width: 100px">是否增值税(可抵扣)</td>
                <td style="min-width: 100px">含税费用金额</td>
                <td style="min-width: 100px">实际投入费用</td>
                <td style="min-width: 100px">预计销量</td>
                <td style="min-width: 100px">预计费用率</td>
                <td style="min-width: 100px">2SR基准销量</td>
                <td style="min-width: 100px">基准销量</td>
                <td style="min-width: 100px">预计ROI</td>
                <td style="min-width: 100px">备注</td>
                <td style="min-width: 100px">状态</td>
                <td style="min-width: 100px">提交人</td>
                <td style="min-width: 100px">修改人</td>
                <td style="min-width: 100px">费用计入部门</td>
                <td style="min-width: 100px">费用计入方案</td>
                <td style="min-width: 100px">收款方</td>
            </tr>
            </thead>
EOF;

        $str .= '<tbody>';
        $i = 0;
        foreach($list as $kk=>$vv) {

            foreach($vv['_child'] as $k=>$v){
                $i++;
                $feetype = $v['feetype'];
                $feetype_title = db('cg_feiyongkemu3')->where('id',$feetype)->value('title');
                $paymethod = $v['paymethod'];
                $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');
                $project = $v['project'];
                $project_title = db('cg_fijiru')->where('id',$project)->value('title');
                $jrbm = $v['jrbm'];
                $jrbm_title = db('cg_fijiruzd t')->join('department t2','t.title = t2.id')->where('t.id',$jrbm)->value('t2.de_name');
                $payee = $v['payee'];
                if($payee==0){
                    $payee = '(经销商)'.db('cg_jxs')->where('id',$jxs_id)->value('title');
                }else{
                    $payee = '(供应商)'.db('gys')->where('id',$v['gys'])->value('gys_name'); //供应商-待做
                }

                if($arealat==2){
                    $net_title = db('cg_net')->where('id',$v['net_id'])->value('title');
                    $mc = "<td>{$net_title}</td>";
                }else{
                    $mc = "<td>{$jxs_title}</td>";
                }
                if($productlat==1){
                    $temp = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==2){
                    $temp = db('pro_category')->where('id',$v['category'])->value('category_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==3){
                    $temp = db('pro_series')->where('id',$v['series'])->value('series_name');
                    $prolat = "<td>{$temp}</td>";
                }elseif($productlat==4){
                    $temp = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
                    $prolat = "<td>{$temp}</td>";
                }else{
                    $temp = db('pro_products')->where('id',$v['product'])->value('pro_name');
                    $prolat = "<td>{$temp}</td>";
                }
                $budan = $v['start']<$v['ctime']?'<span style="display:inline-block;border:1px solid red;color:red;padding:2px 5px;">补单</span>':'';
                $v['start'] = date('Y-m-d',$v['start']);
                $v['end'] = date('Y-m-d',$v['end']);
                $v['expCanTime'] = date('Y-m-d',$v['expCanTime']);
                $v['cuser_name'] = db('employee')->where('id',$v['cuser'])->value('em_name');

                $str .= <<<EOF
        <tr>
            <td>
                <input type="checkbox" name="items" value="{$v['id']}">
            </td>
            <td>
                <button class="btn btn-success upThis" data-id="{$v['id']}">修改</button>
                <button class="btn btn-danger delThis" data-id="{$v['id']}">删除本条</button>
            </td>
            <td>{$i}{$budan}</td>
            <td>{$sn}-{$v['sn']}</td>
            {$mc}
            <td>{$v['start']}-{$v['end']}<input type="hidden" name="end" value="{$v['end']}"><input type="hidden" name="start" value="{$v['start']}"></td>
            <td>{$v['expCanTime']}<input type="hidden" name="expCanTime" value="{$v['expCanTime']}"></td>
            {$prolat}
            <td>{$feetype_title}<input type="hidden" name="feetype" value="{$feetype}"></td>
            <td>{$paymethod_title}<input type="hidden" name="paymethod" value="{$paymethod}"></td>
            <td>{$v['amount']}<input type="hidden" name="amount" value="{$v['amount']}"></td>
            <td>6%</td>
            <td>否</td>
            <td>{$v['hanshui']}</td>
            <td>{$v['yjsjtrfy']}</td>
            <td>{$v['totalExpectedSales']}</td>
            <td>{$v['yujifeiyonglv']}%</td>  
            <td>{$v['2srjizhun']}</td>
            <td>{$v['totalBenchmarkSales']}</td>
            <td>{$v['yujiroi']}</td>
            <td>{$v['brief']}</td>
            <td>正常</td>
            <td>{$v['cuser_name']}</td>
            <td>&nbsp;</td>
            <td>{$jrbm_title}<input type="hidden" name="jrbm" value="{$v['jrbm']}"></td>
            <td>{$project_title}<input type="hidden" name="project" value="{$v['project']}"></td>
            <td>{$payee}<input type="hidden" name="payee" value="{$v['payee']}"></td>
        </tr>
EOF;
            }

            //小计
            $str .= <<<EOF
        <tr>
            <td colspan="2">
            </td>
            <td colspan="4" class="text-right">小计</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$vv['st_amount']}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$vv['st_hanshui']}</td>
            <td>{$vv['st_shijitourufeiyong']}</td>
            <td>{$vv['st_yujixiaoliang']}</td>
            <td>{$vv['st_yujifeiyonglv']}%</td>
            <td>{$vv['st_2srjizhun']}</td>
            <td>{$vv['st_jizhunxiaoliang']}</td>
            <td>{$vv['st_yujiroi']}</td>
            <td colspan="7">&nbsp;</td>
        </tr>
EOF;

        }

        $str .= '</tbody>';
        $str .= <<<EOF
            <tfoot>
                <tr>
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td colspan="4" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">{$st_amount}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">{$st_hanshui}</td>
                <td class="text-right font-bold">{$st_shijitourufeiyong}</td>
                <td class="text-right font-bold">{$st_yujixiaoliang}</td>
                <td class="text-right font-bold">{$st_yujifeiyonglv}%</td>
                <td class="text-right font-bold">{$st_2srjizhun}</td>
                <td class="text-right">{$st_jizhunxiaoliang}</td>
                <td class="text-right">{$st_yujiroi}</td>
                <td colspan="7">&nbsp;</td>
            </tr>
            </tfoot>
EOF;

        return $str;
    }

    //删除行
    /**
     * 修改附件--新增、修改申请时
     * @return mixed
     */
    private function updateAttach(){
        $attach = $this->request->post('attach');
        $id = $this->request->param('id');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }

    public function delItem(){
        $ids = $this->request->param('ids');
        if(!$ids){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti_list')->where('id','in',$ids)->delete();
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    /**
     * 修改附件--异动取消等动作时
     * @return mixed
     */
    private function updateAttach2($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti')->where('id',$id)->value('fb_attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['fb_attach'] = $attach;
        Db::table('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }
    /**
     * 修改附件--核销
     * @return mixed
     */
    private function updateAttach3($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti_hexiao')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti_hexiao')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti_hexiao'));
        }

    }


    /**
     * 修改附件--反馈动作时
     * @return mixed
     */
    private function updateAttach_fb($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('all_ti_feeback_list')->where('id',$id)->value('fujian');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['fujian'] = $attach;
        Db::table('all_ti_feeback_list')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'all_ti_feeback_list'));
        }

    }

    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update($id,$from=1){
        $id = $this->request->param('id');
       
        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');
            $savetype= $this->request->post('savetype');
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }
            $ckfb=db("system_param")->where(["k"=>'chaiFenRenGuiDang'])->value("v");
            if(!$ckfb){
                $data["sfxyfk"]=1;
            }else{
                $data["sfxyfk"]=0;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //修改附件
            $this->updateAttach();

            //修改其他
            $bool = Db::table('cg_ti')->where('id',$id)->update($data);
            if(false !== $bool){

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$id]);
                }
                if($savetype=='save2'){
                  db("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui,yjsjtrfy=hanshui where ti_id=$id");  
                $data['status'] = 3;//提交工作流
                $ys=$this->tiys($id);
                if($ys===0){
                    echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
                }
                if($ys){
                    db("yusuan_detail")->insertAll($ys);
                }
                $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');

                $data2 = [];
                $data2['accessToken'] = session('accessToken');
                $data2['flowId'] = $flowId;
                $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data2);
                $insert = [];
                $insert['ywlx'] = 2;
                $row = db('cg_ti')->where('id',$id)->field('title,sn')->find();
                $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
                $insert['yw_id'] = $id;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
                $insert['sqr_id'] = session('employee_id');
                $insert['workId'] = $data2->workId;
                $insert['trackId'] = $data2->flowNode->trackId;
                db('cg_workflow')->insert($insert);
                $row = db('cg_ti')->where('id',$id)->update(["status"=>3]);
            }
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $this->template();

        $data = Db::table('cg_ti')->where('id',$id)->find();
         $from=$this->request->param("from");
        if(!$from)
            $from=1;
        $this->assign("from",$from);
         if($data["status"]==2){
                    $btn=$this->getbton(2,$data["id"]);
                    //print_r($btn);exit;
                    $this->assign("btn",$btn);
                    $logs=$this->getlog($data["id"]);
                    //print_r($logs);
                    $this->assign("logs",$logs);
                }

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';
        $this->assign('data',$data);
        $this->assign('id',$id);


        $str = $this->feeList($id,$data['arealat'],$data['arealat_title'],$data['productlat'],$data['productlat_title'],$data['jxs_id'],$data['jxs_title'],$data['sn']);
        $this->assign('str',$str);


        //查询供应商数量
        $zj_net_cnt = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $zj_brand_cnt = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $zj_category_cnt = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $zj_series_cnt = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $zj_sku_cnt = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $zj_product_cnt = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $zj_feetype_cnt = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $zj_hanshui  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $zj_yujixiaoliang = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $zj_yujixiaoliang = round($zj_yujixiaoliang,2);
        $zj_yujifeiyonglv = $zj_yujixiaoliang?$zj_hanshui/$zj_yujixiaoliang*100:0;//总计-预计费用率
        $zj_yujifeiyonglv = round($zj_yujifeiyonglv,2);
        $zj_yujiroi = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio

        $zongji = '本申请中包含'.($zj_net_cnt?$zj_net_cnt.'个网点，':'').($zj_brand_cnt?$zj_brand_cnt.'个品牌，':'').($zj_category_cnt?$zj_category_cnt.'个品牌，':'').($zj_series_cnt?$zj_series_cnt.'个系列，':'').($zj_sku_cnt?$zj_sku_cnt.'个sku，':'').($zj_product_cnt?$zj_product_cnt.'个单品，':'').($zj_feetype_cnt?$zj_feetype_cnt.'个三级费用科目，':'').'其中路演费:XXX元；调研费:XXX元;总预计费用:'.$zj_hanshui.'元;总预计销量:'.$zj_yujixiaoliang.'元;总预计费用率:'.$zj_yujifeiyonglv.'%;总ROI:'.$zj_yujiroi.'%;';
        $this->assign('zongji',$zongji);

        //查询附件
        if($data['attach']){
            $attach = unserialize($data['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
            $this->assign('attach',$attach);
        }


        return $this->fetch('form');
    }
    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update_bak(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'arealat|区域纬度'  => 'require',
                'productlat|产品维度'  => 'require',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['arealat'] = $this->request->post('arealat');
            $data['productlat'] = $this->request->post('productlat');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //修改附件
            $this->updateAttach();

            //修改其他
            $bool = Db::table('cg_ti')->where('id',$id)->update($data);
            if(false !== $bool){

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$id]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_ti')->where('id',$id)->find();

        $data['arealat_title'] = $data['arealat']==1?'经销商':'网点';
        $data['productlat_title'] = $data['productlat']==1?'品牌':($data['productlat']==2?'品类':($data['productlat']==3?'系列':($data['productlat']==4?'sku':'单品')));
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $jxs_basic = db('cg_jxs')->where('id',$data['jxs_id'])->field('zoning,provice,city')->find();
        $data['jxs_basic'] = $jxs_basic['zoning'].' '.$jxs_basic['provice'].' '.$jxs_basic['city'].' 性质：经销';
        $this->assign('data',$data);
        $this->assign('id',$id);

        //查询明细列表
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
        foreach($list as $k=>$v){
            $list[$k]['_child'] = db('cg_ti_list')->where('net_id',$v['net_id'])->select();
        }
        dump($list);die;
        $this->assign('list',$list);


        //表格标头
            $mc = "<td style=\"min-width:120px\">{$data['arealat_title']}</td>";
            $prolat = "<td style=\"min-width:100px\">{$data['productlat_title']}</td>";
        $str = <<<EOF
                    <thead>
            <tr class="info">
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td style="min-width:80px">序号</td>
                <td style="min-width:120px">明细编号</td>
                {$mc}
                <td style="min-width: 200px">活动执行时间</td>
                <td style="min-width: 100px">预计核销时间</td>
                {$prolat}
                <td style="min-width: 100px">三级费用科目</td>
                <td style="min-width: 100px">费用支付方式</td>
                <td style="min-width: 100px">未税费用金额</td>
                <td style="min-width: 100px">税率</td>
                <td style="min-width: 100px">是否增值税(可抵扣)</td>
                <td style="min-width: 100px">含税费用金额</td>
                <td style="min-width: 100px">实际投入费用</td>
                <td style="min-width: 100px">预计销量</td>
                <td style="min-width: 100px">预计费用率</td>
                <td style="min-width: 100px">2SR基准销量</td>
                <td style="min-width: 100px">基准销量</td>
                <td style="min-width: 100px">预计ROI</td>
                <td style="min-width: 100px">备注</td>
                <td style="min-width: 100px">状态</td>
                <td style="min-width: 100px">提交人</td>
                <td style="min-width: 100px">修改人</td>
                <td style="min-width: 100px">费用计入部门</td>
                <td style="min-width: 100px">费用计入方案</td>
                <td style="min-width: 100px">收款方</td>
            </tr>
            </thead>
EOF;


        $str .= '<tbody>';
        $subtotal = 0;
        foreach($list as $k=>$v) {
            $feetype = $v['feetype'];
            $feetype_title = db('cg_feiyongkemu3')->where('id',$feetype)->value('title');
            $paymethod = $v['paymethod'];
            $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');
            $project = $v['project'];
            $project_title = db('cg_fijiru')->where('id',$project)->value('title');
            $jrbm = $v['jrbm'];
            $jrbm_title = db('cg_fijiruzd t')->join('department t2','t.title = t2.id')->where('t.id',$jrbm)->value('t2.de_name');
            $payee = $v['payee'];
            if($payee==0){
                $payee = $data['jxs_id'];
            }else{
                $payee = $data['jxs_id']; //供应商-待做
            }
            $paymethod_title = db('cg_paymethod')->where('id',$paymethod)->value('title');

            if($data['arealat']==2){
                $net_title = db('cg_net')->where('id',$v['net_id'])->value('title');
                $mc = "<td>{$net_title}</td>";
            }else{
                $mc = "<td>{$data['jxs_title']}</td>";
            }
            if($data['productlat']==1){
                $temp = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==2){
                $temp = db('pro_category')->where('id',$v['category'])->value('category_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==3){
                $temp = db('pro_series')->where('id',$v['series'])->value('series_name');
                $prolat = "<td>{$temp}</td>";
            }elseif($data['productlat']==4){
                $temp = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
                $prolat = "<td>{$temp}</td>";
            }else{
                $temp = db('pro_products')->where('id',$v['product'])->value('pro_name');
                $prolat = "<td>{$temp}</td>";
            }
            $v['start'] = date('Y-m-d',$v['start']);
            $v['end'] = date('Y-m-d',$v['end']);
            $v['expCanTime'] = date('Y-m-d',$v['expCanTime']);

            $str .= <<<EOF
        <tr>
            <td>
                <input type="checkbox" name="items" value="{$v['id']}">
            </td>
            <td>
                <button class="btn btn-success upThis" data-id="{$v['id']}">修改</button>
                <button class="btn btn-danger delThis" data-id="{$v['id']}">删除本条</button>
            </td>
            <td>{$k}</td>
            <td>{$v['sn']}</td>
            {$mc}
            <td>{$v['start']}-{$v['end']}<input type="hidden" name="end" value="{$v['end']}"><input type="hidden" name="start" value="{$v['start']}"></td>
            <td>{$v['expCanTime']}<input type="hidden" name="expCanTime" value="{$v['expCanTime']}"></td>
            {$prolat}
            <td>{$feetype_title}<input type="hidden" name="feetype" value="{$feetype}"></td>
            <td>{$paymethod_title}<input type="hidden" name="paymethod" value="{$paymethod}"></td>
            <td>{$v['amount']}<input type="hidden" name="amount" value="{$v['amount']}"></td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>  
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>{$jrbm_title}<input type="hidden" name="jrbm" value="{$v['jrbm']}"></td>
            <td>{$project_title}<input type="hidden" name="project" value="{$v['project']}"></td>
            <td>{$payee}<input type="hidden" name="payee" value="{$v['payee']}"></td>
        </tr>
EOF;
        }
        $str .= '</tbody>';
        $str .= <<<EOF
            <tfoot>
                <tr>
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info checkAll">全选</button>
                    <button class="btn btn-success fanxuan">反选</button>
                    <button class="btn btn-danger batchdel">批量删除</button>
                </td>
                <td colspan="3" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td>-</td>
                <td class="text-right">0.00</td>
                <td class="text-right">0.00</td>
                <td colspan="8">&nbsp;</td>
            </tr>
            </tfoot>
EOF;
        $this->assign('str',$str);


        //查询附件
        if($data['attach']){
            $attach = unserialize($data['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch('form');
    }

    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $yuanid=db("cg_ti")->where(["id"=>$id])->value("old");
        if($yuanid){
            db("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
        }
        $bool = Db::table('cg_ti')->where(array('id'=>$id))->delete();
        if(false !== $bool){
            db('cg_ti_list')->where('ti_id',$id)->delete();
             $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$id")->field("yd.id")->select();
              if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                  $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->delete();
              }
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择费用科目3
    public function selectFee(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择费用计入部门
    public function selectJrbm(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择网点
    public function selectNet(){
        return $this->fetch();
    }
    //选择品牌
    public function selectBrands(){
        return $this->fetch();
    }
    //选择品类
    public function selectCategory(){
        return $this->fetch();
    }
    //选择系列
    public function selectSeries(){
        return $this->fetch();
    }
    //选择sku
    public function selectSKU(){
        return $this->fetch();
    }

    //选择单品
    public function selectProduct(){
        return $this->fetch();
    }

    //添加补货明细
    public function addbhlist(){
        if($_POST){
            dump($_POST);
            $data = $this->request->post('data/a');

            foreach($data as $k=>$v){
                $valid = new Valid([
                    'product|样品或物料'=>'require',
                    'num|数量'=>'require|number|>:0',
                ]);
                $bool = $valid->check($v);
                if(false==$bool){
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$valid->getError()
                    ]);die;
                }
            }
            die;
        }
        return $this->fetch();
    }

    //选择我的常用网点
    public function selectMyNetGroup(){

        $where = [];
        $where['cuser'] = Session::get('employee_id');
        $count = Db::table('cg_ti_net_group t')->where($where)->count();
        $data = Db::table('cg_ti_net_group t')->order("t.id desc")->where($where)->paginate(10,$count);

//        echo Db::table('cg_ti')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $t = unserialize($v['net_id']);
            $t = implode(',',$t);
            $t = db('cg_net')->where('id','in',$t)->field('title,id')->select();
            $t2 = [];
            foreach($t as $kk=>$vv){
                $t2[] = $vv['title'];
            }
            $t2 = implode(',',$t2);
            $data[$k]['net_title'] = $t2;
            $data[$k]['net_json'] = json_encode($t);

        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //模板变量
    public function template(){
        //查询我的模板
        $my_t = db('cg_ti_template')->where('cuser',session('employee_id'))->field('id,title')->select();
        $this->assign('my_t',$my_t);

        //全部模板
        $my_t = db('cg_ti_template')->field('id,title')->select();
        $this->assign('all_t',$my_t);


        $my_t_cy = db('cg_ti_template_cy t')->join('cg_ti_template t2','t.tid=t2.id')->where('t.cuser',session('employee_id'))->field('t2.id,t2.title')->order('t.num desc')->limit('5')->select();
        $this->assign('my_t_cy',$my_t_cy);

        //常用模板

    }

    //查看详情
    public function view(){
        $id = $this->request->param('id');
        $logs=$this->getlog($id);
        $this->assign("logs",$logs);
        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');


        //查询明细列表
        if($data['arealat']==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-含税税费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hx_yihexiao'),2);//小计-已核销金额
                $list[$k]['st_shijixiaoliang'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('shijixiaoliang'),2);//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }

        foreach($list as $k=>$v){
            foreach($v['_child'] as $k1=>$v1){
                if($v1['status']==1){ //异动
                    $start = db('cg_ti_list')->where('id',$v1['refer_id'])->value('start');
                    $end = db('cg_ti_list')->where('id',$v1['refer_id'])->value('end');
                    if($start != $v1['start']&&$end!=$v1['end']){
                        $v['_child'][$k1]['start'] = $start;
                        $v['_child'][$k1]['end'] = $end;
                        $v['_child'][$k1]['ydstart'] = $v1['start'];
                        $v['_child'][$k1]['ydend'] = $v1['end'];
                    }
                }
                $v['_child'][$k1]['eauser_title'] = db('employee')->where('id',$v1['eauser'])->value('em_name');
                if($v1['jxs_id']){
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v1['jxs_id'])->value('title');
                }else{
                    $v['_child'][$k1]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.jxs');
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v['_child'][$k1]['jxs_id'])->value('title');
                }
                $v['_child'][$k1]['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v['_child'][$k1]['paymethod_title'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');

                $v['_child'][$k1]['jrbm_puser_name'] = db('cg_fijiruzd t')
                    ->join('employee t2','t2.id=t.puser')
                    ->where('t.title',$v1['jrbm'])
                    ->value('t2.em_name');//费用计入部门修改人
                $v['_child'][$k1]['jrbm'] = db('department t')
                    ->join('cg_fijiruzd t2','t2.title = t.id')
                    ->where('t2.id',$v1['jrbm'])
                    ->value('t.de_name');

                $v['_child'][$k1]['jrbm_dp'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $v['_child'][$k1]['jrbm_dp_puser'] = db('cg_fijiru t')->join('employee t2','t2.id=t.puser')->where('t.id',$v1['project'])->value('t2.em_name');
                $v['_child'][$k1]['brand'] = db('pro_brands')->where('id',$v1['brand'])->value('brand_name');
                if($v1['net_id'])
                    $v['_child'][$k1]['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $v['_child'][$k1]['productlatval'] = $this->productlatval($v1);
                $v['_child'][$k1]['yujifeiyonglv'] = $v1['totalExpectedSales']?round($v1['yjsjtrfy']/$v1['hanshui'],2)*100:0;
                $v['_child'][$k1]['xiaoshoudachenglv'] = $v1['totalExpectedSales']?round($v1['fb_shijixiaoliang']/$v1['totalExpectedSales'],2)*100:0;
                $v['_child'][$k1]['gys_name'] = db('gys')->where('id',$v1['gys'])->value('gys_name');
            }
            $list[$k] = $v;
        }

        $data['list'] = $list;

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }

        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yjsjtrfy');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['yujixiaoliang']?$data['hanshui']/$data['yujixiaoliang']*100:0;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio
        $data['yihexiao'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao'),2);//总计-已核销
        $data['shijixiaoliang'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang'),2);//总计-实际销量
        $data['xiaoshoudachenglv'] = $data['yujixiaoliang']?$data['shijixiaoliang']/$data['yujixiaoliang']*100:0;

        $data['yhx'] = db('cg_ti_hexiao_list t')
            ->join('cg_ti_list t2','t2.id=t.list_id')
            ->where('t2.ti_id',$id)->count();
//        echo db('cg_ti_list')->getLastSql();
            
        $this->assign('data',$data);
         $fei=db("cg_ti_list")->alias("t")->join("cg_feiyongkemu3 f3","t.feetype=f3.id")->group("f3.id")->where(["ti_id"=>$id])->field("f3.title,sum(pizhunhanshui) as jine")->select();
        $this->assign("fei",$fei);
        //查询审批意见
        $wf_id = db('cg_workflow')->where(['ywlx'=>2,'yw_id'=>$id])->value('id');
        $spyj = db('cg_workflow_spyj')->where('wf_id',$wf_id)->order('spsj asc')->select();
        $this->assign('spyj',$spyj);

        $export = $this->request->get('export');
        if($export){

            //根据经销商查询分区省份和城市
            $city = db('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $provice = db('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $zoning = db('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $this->assign([
                'city'=>$city,
                'provice'=>$provice,
                'zoning'=>$zoning,
            ]);

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.iconv('utf-8','gbk',$data['sn'].'-'.date("Y年m月j日")).'.xls"');
            return $this->fetch('view_export');
        }else{
            //查询核销编号
            $hxsn = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where('t3.ti_id',$id)
                ->field('t.id,t.sn')
                ->select();
            $this->assign('hxsn',$hxsn);
            //查询反馈编号
            $fbsn = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->where(['type'=>1,'t2.id'=>$id])
                ->field('t.id,t.no')
                ->find();
            $this->assign('fbsn',$fbsn);
            return $this->fetch();
        }
    }

    //异动
    public function yd(){
        $id = $this->request->param('id');

        //提交表单
        if($_POST){
            $post_data = $this->request->post('data/a');
            $type = $this->request->post('type');
            //验证异动原因
            $bool = true;
            $oldmxids = [];//异动明细的ids
            foreach($post_data as $k=>$v){
                if(!empty($v['ydreason'])){
                    $bool = false;
                }
                if($v['start']!=''&&$v['end']!=''){
                    if(strtotime($v['start'])>strtotime($v['end'])){
                        echo json_encode(['success'=>false,'msg'=>'活动执行开始时间不能大于结束时间']);die;
                    }
                }
                if($v['end']!=''&&$v['expCanTime']!=''){
                    if(strtotime($v['end'])>strtotime($v['expCanTime'])){
                        echo json_encode(['success'=>false,'msg'=>'预计核销时间不能小于活动结束时间']);die;
                    }
                }
                $oldmxids[] = $v['id'];
            }
            if($bool==true){
                echo json_encode(['success'=>false,'msg'=>'请填写异动原因']);die;
            }

            $insert_sn = $this->produceSN();//生成编号

            $ti = db('cg_ti')->where('id',$id)->field('title,arealat,productlat,jxs_id,attach')->find();

            $insert = [
                'sn'=>$insert_sn,
                'title'=>$ti['title'],
                'arealat'=>$ti['arealat'],
                'productlat'=>$ti['productlat'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
                'old'=>$id,
                'cate_id'=>2//类型 2异动
            ];
            $savetype=1;
            if($type=='save2'){
                //$insert['status']=3; //提交工作流，区域领导审批
                $savetype=3;
            }

            $ti_id = db('cg_ti')->insertGetId($insert);//生成新纪录
            //修改附件
            $this->updateAttach2($ti_id);

            db('cg_ti')->where('id',$id)->update(['is_ydqx'=>1]);//更新旧记录

            $old = db('cg_ti_list')
                ->where('ti_id',$id)
                ->select();

            //构造插入数据
            foreach($old as $k=>$v){
                if(in_array($v['id'],$oldmxids)){
                    foreach($post_data as $k1=>$v1){
                        if($v['id']==$v1['id']){
                            $v = array_merge($v,$v1);
                            $v['start'] = strtotime(trim($v1['start']));
                            $v['end'] = strtotime(trim($v1['end']));
                            $v['expCanTime'] = strtotime(trim($v1['expCanTime']));
                            $v['refer_id'] =  $v1['id'];
                            $v['status'] = 1;//0正常，1已异动
                            $v["pizhunweishui"]=$v1["amount"];
                            $v["pizhunhanshui"]=$v1["hanshui"];
                            if($v1["isVAT"]){
                                $v["yjsjtrfy"]=$v1["amount"];
                            }else{
                                $v["yjsjtrfy"]=$v1["hanshui"];
                            }
                            $v["yujifeiyonglv"]=$v["yjsjtrfy"]/$v["totalExpectedSales"]*100;
                            if($v["product"]){
                                $profit=db("pro_products pp")->join("pro_sku sk","pp.sku_id=sk.id")
                                ->join("pro_series ps","sk.series_id=ps.id")->join("pro_category pc","ps.category_id=pc.id")
                                ->join("pro_brands pb","pc.brand_id=pb.id")->where(["pp.id"=>$v["product"]])->value("pb.profit");
                            }else if($v["sku"]){
                                $profit=db("pro_sku sk")
                                ->join("pro_series ps","sk.series_id=ps.id")->join("pro_category pc","ps.category_id=pc.id")
                                ->join("pro_brands pb","pc.brand_id=pb.id")->where(["sk.id"=>$v["sku"]])->value("pb.profit");
                            }else if($v["series"]){
                                $profit=db("pro_series ps")->join("pro_category pc","ps.category_id=pc.id")
                                ->join("pro_brands pb","pc.brand_id=pb.id")->where(["ps.id"=>$v["series"]])->value("pb.profit");
                            }else if($v["category"]){
                                $profit=db("pro_category pc")
                                ->join("pro_brands pb","pc.brand_id=pb.id")->where(["pc.id"=>$v["category"]])->value("pb.profit");
                            }else{
                                $profit=db("pro_brands pb")->where(["pb.id"=>$v["brand"]])->value("pb.profit");
                            }
                            $v["yujiroi"]=($v["totalExpectedSales"]-$v["totalBenchmarkSales"])*$profit/100/$v["yjsjtrfy"];
                        }
                    }
                }

                $v['cuser'] = session('employee_id');
                $v['puser'] = session('employee_id');
                $v['ctime'] =  time();
                $v['ptime'] =  time();
                $v['ti_id'] =  $ti_id;
                $v['ydstart'] =  null;
                $v['ydend'] =  null;
                unset($v['id']);//删除id
                $old[$k] = $v;
            }
            $bool = db('cg_ti_list')->insertAll($old);
              $ys=$this->tiys($ti_id);
                    if($ys===0&&$savetype==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                    //$res1 = Db::table("cg_ti")->update($dataup);

                   
                    if ($savetype == 3) {
                        if($ys){
                            Db::table("yusuan_detail")->insertAll($ys);
                        }
                        
                    }
                    if($savetype==3){
                    $flowId = db('cg_workflowset')->where(['id' => '21'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    $insert['ywlx'] = 21;
                    $row = db('cg_ti')->where('id', $ti_id)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $ti_id;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $ti_id)->update(["status"=>3]);
                }
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        $data['list'] = db('cg_ti_list')->where('ti_id',$id)->order('net_id asc')->select();
        foreach($data['list'] as $k=>$v){
            $data['list'][$k]['eauser_title'] = db('employee')->where('id',$v['eauser'])->value('em_name');
            if($v['jxs_id']){
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$v['jxs_id'])->value('title');
            }else{
                $data['list'][$k]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->value('t.jxs');
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$data['list'][$k]['jxs_id'])->value('title');
            }
            $data['list'][$k]['feetype'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $data['list'][$k]['paymethod_title'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $data['list'][$k]['jrbm'] = db('department t')->join('cg_fijiruzd t2','t2.title = t.id')->where('t2.id',$v['jrbm'])->value('t.de_name');
            $data['list'][$k]['jrbm_dp'] = db('cg_fijiru')->where('id',$v['project'])->value('title');
            $data['list'][$k]['brand'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            if($v['net_id'])
                $data['list'][$k]['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $data['list'][$k]['productlatval'] = $this->productlatval($v);
            $data['list'][$k]['gys_name'] = db('gys')->where('id',$v['gys'])->value('gys_name');
        }

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yjsjtrfy');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['hanshui']/$data['yujixiaoliang']*100;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi');//总计-预计rio
        $data['yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao');//总计-已核销
        $data['shijixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang');//总计-实际销量

//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);

        //查询附件
        $attach = Db::table('cg_ti')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch();
    }

    //经销商
    public function jxsview(){
        return $this->fetch();
    }
    //明细详情
    public function dataview(){
        $id = $this->request->param('id');
        $data = db('cg_ti_list')->where('id',$id)->find();
        $this->assign('data',$data);
        $apply=Db::table("cg_ti")->where(["id"=>$data["ti_id"]])->find();
        $this->assign("apply",$apply);
        $fb = Db::table("all_ti_feeback_list")->where(["apply_id" => $apply["id"], "type" => 1, "is_deleted" => 0, "is_actived" => 1])->find();
        $this->assign("fb",$fb);
        return $this->fetch();
    }
    //决策依据
    public function decisionbasis(){
        return $this->fetch();
    }

    //提交工作流
    public function subworkflow(){
        $id = $this->request->param('id');
        $cate_id=db("cg_ti")->where(["id"=>$id])->value("cate_id");
        if($cate_id==1){
            db("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui,yjsjtrfy=hanshui where ti_id=$id");
            $ywlx=2;
        }else if($cate_id==2){
            $ywlx=21;
        }else
            $ywlx=22;
        
        //echo $id;exit;
        $ys=$this->tiys($id);
        if($ys===0){
            echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
        }
        if($cate_id==1)
            $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');
        else if($cate_id==2)
            $flowId = db('cg_workflowset')->where(['id'=>'21'])->value('flow_id');
        else if($cate_id==3)
            $flowId = db('cg_workflowset')->where(['id'=>'22'])->value('flow_id');
        $data = [];
        $data['accessToken'] = session('accessToken');
        $data['flowId'] = $flowId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data);
        if($data->flowMsg=='提交成功'){
            $insert = [];
            $insert['ywlx'] = $ywlx;
            $row = db('cg_ti')->where('id',$id)->field('title,sn')->find();
            $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
            $insert['yw_id'] = $id;
            $insert['status'] = 1;
            $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
            $insert['sqr_id'] = session('employee_id');
            $insert['workId'] = $data->workId;
            $insert['trackId'] = $data->flowNode->trackId;
            db('cg_workflow')->insert($insert);
        }else{
            echo json_encode(['success'=>false,'msg'=>$data->flowMsg]);die;
        }
        if($ys){
            Db::table("yusuan_detail")->insertAll($ys);
       }
        $bool = db('cg_ti')->where('id',$id)->update(['status'=>3]);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'提交成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'提交失败']);
        }
    }

    //根据id查找状态
    public function status($id){
        $data = [
            1=>'草稿',
            2=>'已打回',
            3=>'区域领导审批',
            4=>'拆分人审批',
            5=>'集团领导审批',
            6=>'抄送',
            7=>'已归档',
            8=>'已作废',
            9=>'已否决',
        ];
        return $data[$id];
    }

    //根据id查找产品纬度标题
    public function productlat($id){
        $data = [
            1=>'品牌',
            2=>'品类',
            3=>'系列',
            4=>'SKU',
            5=>'单品',
        ];
        return $data[$id];
    }

    //根据id查找产品纬度值
    public function productlatval($v){
        if($v['brand']){
            return db('pro_brands')->where('id',$v['brand'])->value('brand_name');
        }elseif($v['category']){
            return db('pro_category')->where('id',$v['category'])->value('category_name');
        }elseif($v['series']){
            return db('pro_series')->where('id',$v['series'])->value('series_name');
        }elseif($v['sku']){
            return db('pro_sku')->where('id',$v['sku'])->value('sku_name');
        }elseif($v['product']){
            return db('pro_products')->where('id',$v['product'])->value('pro_name');
        }
    }

    //取消
    public function cancel(){
        $id = $this->request->param('id');

        //提交表单
        if($_POST){

            //原单保持原样，取消的部分和未取消的部分分别生成新单
            $post_data = $this->request->post('data/a');
            $type = $this->request->post('type');

            //验证
            $ids = [];
            foreach($post_data as $k=>$v){

                if(trim($v['reason'])==''){
                    echo json_encode(['success'=>false,'msg'=>'请填写取消原因']);die;
                }
                $ids[] = $v['id'];

            }

            $ti = db('cg_ti')->where('id',$id)->find();
            //生成新的取消申请单
            $newSN = $this->produceSN();
            $insert = [
                'sn'=>$newSN,
                'title'=>$ti['title'],
                'arealat'=>$ti['arealat'],
                'productlat'=>$ti['productlat'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
                'old'=>$id,
                'cate_id'=>3 //类型,3取消
            ];
            $insert['status']=1; //提交工作流，区域领导审批
            $statustype=1;
            if($type=='save2'){
                $statustype=3;
            }
            $bool = true;
            //生成新的取消后申请单
            $new_ti_id = db('cg_ti')->insertGetId($insert);

            //修改附件
            $this->updateAttach2($new_ti_id);

            //生成新的取消后明细
            $insert = [];
            foreach($post_data as $k=>$v){
                $row = db('cg_ti_list')->where('id',$v['id'])->find();
                $row['ctime'] = time();
                $row['ptime'] = time();
                $row['cuser'] = Session::get('employee_id');
                $row['puser'] = Session::get('employee_id');
                $row['ti_id'] = $new_ti_id;
                if(trim($v['reason'])){
                    $row['cancel_reason'] = $v['reason'];
                }

                $row['status'] = 2;//0正常，1已异动，2已取消
                $row['refer_id'] = $row['id'];//对应的原单
                unset($row['id']);
                $insert[] = $row;
            }

            db('cg_ti_list')->insertAll($insert);

            //原单子标记为取消
            $temp_bool = db('cg_ti')->where('id',$id)->update(['is_ydqx'=>1]);
            if($temp_bool===false)
                $bool = false;
            //判断工作流
             if($statustype==3){
                    $flowId = db('cg_workflowset')->where(['id' => '22'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    $insert['ywlx'] = 22;
                    $row = db('cg_ti')->where('id', $new_ti_id)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $new_ti_id;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $new_ti_id)->update(["status"=>3]);
                }
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        $data['list'] = db('cg_ti_list')->where('ti_id',$id)->order('net_id asc')->select();
        foreach($data['list'] as $k=>$v){
            $data['list'][$k]['eauser_title'] = db('employee')->where('id',$v['eauser'])->value('em_name');
            if($v['jxs_id']){
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$v['jxs_id'])->value('title');
            }else{
                $data['list'][$k]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->value('t.jxs');
                $data['list'][$k]['jxs_title'] = db('cg_jxs')->where('id',$data['list'][$k]['jxs_id'])->value('title');
            }
            $data['list'][$k]['feetype'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $data['list'][$k]['paymethod_title'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $data['list'][$k]['jrbm'] = db('department t')->join('cg_fijiruzd t2','t2.title = t.id')->where('t2.id',$v['jrbm'])->value('t.de_name');
            $data['list'][$k]['jrbm_dp'] = db('cg_fijiru')->where('id',$v['project'])->value('title');
            $data['list'][$k]['brand'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            if($v['net_id'])
                $data['list'][$k]['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $data['list'][$k]['productlatval'] = $this->productlatval($v);
            $data['list'][$k]['gys_name'] = db('gys')->where('id',$v['gys'])->value('gys_name');
        }

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        $data['productlat_title'] = $this->productlat($data['productlat']);
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');

        $this->assign('data',$data);

        //查询附件
        $attach = Db::table('cg_ti')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch();
    }

    //roi报告
    public function roireport(){
        return $this->fetch();
    }
    //反馈
    public function feedback(){
        $id = $this->request->param('id');
        $feedbacktype = $this->request->param('feedbacktype');

        if($_POST){
            if($feedbacktype==0){ //整单反馈
                $actualSales = $this->request->post('actualSales');
                $brief = $this->request->post('brief');
                $arr = $this->request->post('arr/a');

                //验证并构造新数组
                $new_arr = [];
                foreach($arr as $k=>$v){
                    if(empty($v['feetype'])){
                        echo json_encode(['success'=>false,'msg'=>'参数错误']);die;
                    }
                    if(empty($v['real_hanshui'])){
                        echo json_encode(['success'=>false,'msg'=>'实际含税金额不能为空']);die;
                    }
                    if($v['real_shuilv']==''){
                        echo json_encode(['success'=>false,'msg'=>'税率不能为空']);die;
                    }
                    if($v['isVAT']==''){
                        echo json_encode(['success'=>false,'msg'=>'请选择是否增值税']);die;
                    }
                    $arr[$k]['ti_id'] = $id;
                    $arr[$k]['cuser'] = session('employee_id');
                    $arr[$k]['puser'] = session('employee_id');
                    $arr[$k]['ctime'] = time();
                    $arr[$k]['ptime'] = time();
                    $new_arr[$v['feetype']] = $arr[$k];
                }

                //拆分数据
                $mingxi = db('cg_ti_list')
                    ->where('ti_id',$id)
                    ->group('feetype')
                    ->field('feetype')
                    ->select();

                $bool = true;
                //计算平均实际总销量
                $cnt = db('cg_ti_list')->where('ti_id',$id)->count();
                $avgsales = round($actualSales/$cnt,2);
                foreach($mingxi as $k=>$v){
                    //计算实际和预期的比例
                    //查询明细个数
                    $cnt = db('cg_ti_list')
                        ->where(['feetype'=>$v['feetype'],'ti_id'=>$id])
                        ->count();
                    //计算平均每个实际金额
                    $meigeshiji = $new_arr[$v['feetype']]['real_hanshui']/$cnt;
                    $shijiweishui = round($meigeshiji/(1+$new_arr[$v['feetype']]['real_shuilv']/100),2); //实际未税金额

                    $shuilv = $new_arr[$v['feetype']]['real_shuilv'];
                    $isVAT = $new_arr[$v['feetype']]['isVAT'];
                    if($isVAT){
                        $sj=$shijiweishui;
                    }else{
                        $sj=$meigeshiji;
                    }
                    //更新该费用分类下的明细的实际含税金额
                    $bool2 = db('cg_ti_list')
                        ->where(['feetype'=>$v['feetype'],'ti_id'=>$id])
                        ->update([
                            'fb_shijitourufeiyong'=>$sj,
                            'fb_hanshui'=>$meigeshiji,
                            'fb_shijiweishui'=>$shijiweishui,
                            'fb_shuilv'=>$shuilv,
                            'fb_isVAT'=>$isVAT,
                            'fb_shijixiaoliang'=>$avgsales,
                            'fb_brief'=>$brief,
                            'hx_status'=>5
                            ]);
                    if(false === $bool2){
                        $bool = false;
                    }
                }

                //反馈到cg_ti
                $bool2 = db('cg_ti')
                    ->where('id',$id)
                    ->update(['fb'=>1, //是否反馈，0否，1是
                        'fb_cate'=>1,//反馈类型，1整单，2网点
                        'fb_actualSales'=>$actualSales,//实际费用
                        'fb_brief'=>$brief] //备注
                    );

                if(false === $bool2){
                    $bool = false;
                }

                //反馈到all_ti_feeback_list
                $fb_id = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$id])
                    ->value('id');
                $fb_id=0;
                if($fb_id==0){
                    $newSN = $this->producefbSN();
                    $insert = [
                        'no'=>$newSN,
                        'type'=>1,
                        'apply_id'=>$id,
                        'c_user_id'=>session('employee_id'),
                        'created_on'=>date('Y-m-d H:i:s'),
                        'is_deleted'=>0,
                        'is_actived'=>1,
                        'state'=>1,
                        'remark'=>$brief
                    ];
                    $type = $this->request->post('savetype');
                    
                    $fb_id = db('all_ti_feeback_list')->insertGetId($insert);
                    if(false===$fb_id){
                        $bool = false;
                    }
                    if($type=='save2'){
                        //$insert['state']=3; //提交工作流，区域领导审批
                         $jieguo=$this->gowork(17,$fb_id);
                    }

                    //反馈到cg_ti
                    $bool2 = db('cg_ti')
                        ->where('id',$id)
                        ->update(['fd_id'=>$fb_id]);

                    if(false===$bool2){
                        $bool = false;
                    }
                }

                //修改附件
                $this->updateAttach_fb($fb_id);

                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'反馈成功']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'反馈失败']);
                }
            }else{ //按网点反馈提交
                $brief = $this->request->post('brief');
                $arr = $this->request->post('arr/a');

                //验证
                foreach($arr as $k=>$v){
                    if(empty($v['realsales'])){
                        echo json_encode(['success'=>false,'msg'=>'实际总销量不能为空']);die;
                    }
                    if(empty($v['realamount'])){
                        echo json_encode(['success'=>false,'msg'=>'实际未税金额不能为空']);die;
                    }
                    if($v['real_shuilv']==''){
                        echo json_encode(['success'=>false,'msg'=>'税率不能为空']);die;
                    }
                    if($v['isVAT']==''){
                        echo json_encode(['success'=>false,'msg'=>'请选择是否增值税']);die;
                    }

                }

                $productlat = $this->request->post('productlat');
                switch ($productlat){
                    case 1:
                        $product = 'brand';
                        break;
                    case 2:
                        $product = 'category';
                        break;
                    case 3:
                        $product = 'series';
                        break;
                    case 4:
                        $product = 'sku';
                        break;
                    case 5:
                        $product = 'product';
                        break;
                }
                $bool = true;
                //反馈到cg_ti_list
                foreach($arr as $k=>$v){
                    $cnt = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id'],$product=>$v['pid']])
                        ->count();
                    $fb_shijixiaoliang = round($v['realsales']/$cnt,2); //实际销量
                    $fb_realamount = round($v['realamount']/$cnt,2); //实际未税
                    $shijihanshui = round($fb_realamount*(1+$v['real_shuilv']/100),2); //实际含税金额
                    //计算实际销量的平均值
                    $bool2 = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id'],$product=>$v['pid']])
                        ->update([
                           'fb_shijixiaoliang'=>$fb_shijixiaoliang,
                           'fb_shijiweishui'=>$fb_realamount,
                           'fb_shuilv'=>$v['real_shuilv'],
                           'fb_isVAT'=>$v['isVAT'],
                           'fb_shijitourufeiyong'=>$shijihanshui,
                            'fb_brief'=>$brief,
                            'fb_time'=>time(),
                            'fb_user'=>time(),
                        'hx_status'=>5
                        ]);
                    if(false===$bool2){
                        $bool = false;
                    }
                }
                //反馈到cg_ti
                $bool2 = db('cg_ti')
                    ->where('id',$id)
                    ->update(['fb'=>1,'fb_cate'=>2,'fb_brief'=>$brief]);
                if(false===$bool2){
                    $bool = false;
                }

                //反馈到all_ti_feeback_list
                $fb_id = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$id])
                    ->count();
                if($fb_id==0){
                    $newSN = $this->producefbSN();
                    $type = $this->request->post('savetype');
                    $insert = [
                        'no'=>$newSN,
                        'type'=>1,
                        'apply_id'=>$id,
                        'c_user_id'=>session('employee_id'),
                        'created_on'=>date('Y-m-d H:i:s'),
                        'is_deleted'=>0,
                        'is_actived'=>1,
                        'state'=>2,
                        'remark'=>$brief,
                    ];
                    if($type=='save2'){
                        $insert['state']=3; //提交工作流，区域领导审批
                    }
                    $fb_id = db('all_ti_feeback_list')->insertGetId($insert);
                    if(false===$fb_id){
                        $bool = false;
                    }

                    //反馈到cg_ti
                    $bool2 = db('cg_ti')
                        ->where('id',$id)
                        ->update(['fd_id'=>$fb_id]);

                    if(false===$bool2){
                        $bool = false;
                    }
                }

                //修改附件
                $this->updateAttach_fb($fb_id);

                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'反馈成功']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'反馈失败']);
                }
            }

            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();

        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');

        if($feedbacktype=='0'){ //整单反馈
            //区域纬度
            if($data['arealat'] == 1){
                $arealat = '经销商数';
            }else{
                $arealat = '网点数';
            }

            //产品纬度
            if($data['productlat'] == 1){
                $productlat = '品牌数';
            }elseif($data['productlat'] == 2){
                $productlat = '品类数';
            }elseif($data['productlat'] == 3){
                $productlat = '系列数';
            }elseif($data['productlat'] == 4){
                $productlat = 'sku数';
            }elseif($data['productlat'] == 5){
                $productlat = '产品数';
            }

            $this->assign([
                'arealat'=>$arealat,
                'productlat'=>$productlat
            ]);

            //按照费用科目做统计
            $list = db('cg_ti_list')->where('ti_id',$id)->group('feetype')->select();
            foreach($list as $k=>$v){
                $list[$k]['feetype_title'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');

                //区域纬度
                if($data['arealat'] == 1){
                    $list[$k]['arealats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('jxs_id');
                }else{
                    $list[$k]['arealats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('net_id');
                }

                //产品纬度
                if($data['productlat'] == 1){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('brand');
                }elseif($data['productlat'] == 2){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('category');
                }elseif($data['productlat'] == 3){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('series');
                }elseif($data['productlat'] == 4){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('sku');
                }elseif($data['productlat'] == 5){
                    $list[$k]['productlats'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->count('product');
                }

                //预计含税金额
                $list[$k]['amounts'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('hanshui');
            }
            $data['hanshuis'] = db('cg_ti_list')->where('ti_id',$id)->sum('hanshui');
            $data['list'] = $list;
        }else{ //按照网点反馈
            //区域纬度
            if($data['arealat'] == 1){
                $arealat1 = '经销商编号';
                $arealat2 = '经销商名称';
            }else{
                $arealat1 = '网点编号';
                $arealat2 = '网点名称';
            }
            //产品纬度
            if($data['productlat'] == 1){
                $productlat = '品牌';
            }elseif($data['productlat'] == 2){
                $productlat = '品类';
            }elseif($data['productlat'] == 3){
                $productlat = '系列';
            }elseif($data['productlat'] == 4){
                $productlat = 'sku';
            }elseif($data['productlat'] == 5){
                $productlat = '产品';
            }
            $this->assign([
                'arealat1'=>$arealat1,
                'arealat2'=>$arealat2,
                'productlat'=>$productlat
            ]);

            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->select();

            $list2 = [];
            foreach($list as $k=>$v){

                $arealat_sn = db('cg_net')->where('id',$v['net_id'])->value('sn');
                $arealat_title = db('cg_net')->where('id',$v['net_id'])->value('title');

                //按照产品分组
                if($data['productlat'] == 1){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id']])
                        ->group('brand')
                        ->field('net,brand p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_brands')->where('id',$v1['p_id'])->value('brand_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 2){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id']])
                        ->group('category')
                        ->field('net,category p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_category')->where('id',$v1['p_id'])->value('category_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 3){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id']])
                        ->group('series')
                        ->field('net,series p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_series')->where('id',$v1['p_id'])->value('series_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 4){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id']])
                        ->group('sku')
                        ->field('net,sku p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_sku')->where('id',$v1['p_id'])->value('sku_name');
                        $list2[] = $v1;
                    }
                }elseif($data['productlat'] == 5){
                    $product = db('cg_ti_list')
                        ->where(['ti_id'=>$id,'net_id'=>$v['net_id']])
                        ->group('product')
                        ->field('net,product p_id,sum(totalExpectedSales) yujixiaoliang,sum(hanshui) yujitouru')
                        ->select();
                    foreach($product as $k1=>$v1){
                        $v1['arealat_sn'] = $arealat_sn;
                        $v1['arealat_title'] = $arealat_title;
                        $v1['productlat_title'] = db('pro_products')->where('id',$v1['p_id'])->value('pro_name');
                        $list2[] = $v1;
                    }
                }
            }
            $data['list'] = $list2;
            $data['totalExpectedSales'] = round(db('cg_ti_list')->where('ti_id',$id)->sum('totalExpectedSales'),2);
            $data['totalAmount'] = round(db('cg_ti_list')->where('ti_id',$id)->sum('amount'),2);

        }

        $this->assign('data',$data);
        if($feedbacktype == 0){
            return $this->fetch();
        }else{
            return $this->fetch('feedbackbynet');
        }
    }

    //核销-按照网点核销
    public function writeoff(){
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type');
        $where = [];

        switch(intval($type)){
            case 1: //核销中
                $hx_ids = db('cg_ti_hexiao')->where('status',1)->column('id');
                $list_ids = db('cg_ti_hexiao_list')->where('hx_id','in',$hx_ids)->column('list_id');
                $where['id'] = ['in',$list_ids];
                $where['ti_id'] = ['in',$tiids];
                break;
            case 3: //未反馈
                //已反馈
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
                $fb_ids = implode(',',$fb_ids);
                $ti_ids = db('cg_ti')->where(['status'=>7])->column('id');
                $ti_ids = implode(',',$ti_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"not in($fb_ids) and ti_id in($ti_ids) and ti_id in($tiids)"];
                break;
            case 2: //不予核销
            case 4: //未核查
            case 5: //已锁定
                $where['hx_status'] = $type;
                $where['ti_id'] = ['in',$tiids];
                break;
            default: //可核销
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
//                echo db('cg_ti')->getLastSql();
                $fb_ids = implode(',',$fb_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"in($fb_ids) and ti_id in($tiids)"];
                $where['ti_id'] = ['in',$tiids];
                $where['hx_status'] = ['<>',2];
        }

        //查询申请单
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['jxs_sn'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('sn');
        $list = db('cg_ti_list')->where($where)->limit(0,10)->select();
//        echo db('cg_ti_list')->getLastSql();

        $data['area_title'] = '网点名称';
        $data['area_title2'] = '系统名称';

        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }else{
            $data['product_title'] = '品牌';
        }
        foreach($list as $k=>$v){
            if($v['net_id']){
                $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
                $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            }else{
                $v['net_title'] = '无';
                $v['system_title'] = '无';
            }

            if($data['productlat']==1) { //品牌
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($data['productlat']==2) { //品类
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($data['productlat']==3) { //系列
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($data['productlat']==4) { //sku
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }elseif($data['productlat']==5){
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }elseif($v['tm_id']){
                $v['product_name'] = Db::table("pro_products")->alias("p")
                    ->join("pro_sku sk","p.sku_id=sk.id")
                    ->join("pro_series s","sk.series_id=s.id")
                    ->join("pro_category c","s.category_id=c.id")
                    ->join("pro_brands b","c.brand_id=b.id")
                    ->where('p.id',$v['tm_id'])
                    ->value('b.brand_name');
            }
            $v['shijitourujine'] = $v['fb_shijiweishui'];
            $v['weihexiaojine'] = $v['shijitourujine']-$v['hx_yihexiao'];
            $v['cate_name'] = db('cg_ti_cate t')->join('cg_ti t2','t2.cate_id=t.id')->where('t2.id',$v['ti_id'])->value('t.title');
            $list[$k] = $v;
        }

        foreach($list as $k=>$v){
            if($v['start']){
                $v['huodongkaishiriqi'] = $v['start'];
            }else{
                $v['huodongkaishiriqi'] = strtotime($v['year'].'-'.$v['month'].'-'.'1');
            }
            $list[$k] = $v;
        }

        if(intval($type)==1){
            //核销中
            foreach($list as $k=>$v){
                $t = db('cg_ti_hexiao_list')
                    ->where('list_id',$v['id'])
                    ->field('shijitourujine y_shijitourujine,weishuihexiaojine,youwufapiao,fapiaohao,shuilv hx_shuilv,shuijin,isVAT hx_isVAT,hanshuihexiaojine hx_hanshuihexiaojine,shijitourujine hx_shijitourujine,yuebuhexiao,huodongkaishiriqi,beizhu hx_beizhu')
                    ->find();
                $v = array_merge($v,$t);
                $list[$k] = $v;
            }
        }

        $data['list'] = $list;
        $this->assign('data',$data);

        //查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);
        return $this->fetch();
    }

    //按照整单核销
    public function writeoff2(){
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type'); //状态
        $where = [];

        switch(intval($type)){
            case 1: //核销中
                $hx_ids = db('cg_ti_hexiao')->where('status',1)->column('id');
                $list_ids = db('cg_ti_hexiao_list')->where('hx_id','in',$hx_ids)->column('list_id');
                $where['id'] = ['in',$list_ids];
                $where['ti_id'] = ['in',$tiids];dump($type);
                break;
            case 3: //未反馈
                //已反馈
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
                $fb_ids = implode(',',$fb_ids);
                $ti_ids = db('cg_ti')->where(['status'=>7])->column('id');
                $ti_ids = implode(',',$ti_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"not in($fb_ids) and ti_id in($ti_ids) and ti_id in($tiids)"];
                break;
            case 2: //不予核销
            case 4: //未核查
            case 5: //已锁定
                $where['hx_status'] = $type;
                $where['ti_id'] = ['in',$tiids];
                break;
            default: //可核销
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
//                echo db('cg_ti')->getLastSql();
                $fb_ids = implode(',',$fb_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"in($fb_ids) and ti_id in($tiids)"];
                $where['hx_status'] = ['<>',2];
        }

        //查询申请单
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['jxs_sn'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('sn');
        $list = db('cg_ti_list')->where($where)->group('ti_id,paymethod')->limit(0,10)->select(); //先加载两条
        //echo db('cg_ti_list')->getLastSql();
        $data['area_title'] = '网点';
        $data['product_title'] = '产品纬度';

        foreach($list as $k=>$v){
            $v['ti_title'] = db('cg_ti')->where('id',$v['ti_id'])->value('title');
            $v['ti_ctime'] = db('cg_ti')->where('id',$v['ti_id'])->value('ctime');
            if($data['arealat']==2) { //区域纬度选择经销商
                //网点个数
                $v['net_num'] = db('cg_ti_list')
                    ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                    ->count('DISTINCT net');
            }
            //费用科目
            $v['feetype'] = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->count('DISTINCT feetype');

            //产品纬度个数
            $temp = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT brand');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT category');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT series');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT sku');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT product');

            $v['product_name'] = $temp;

            $v['shijitourujine'] = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('fb_shijitourufeiyong');
            $v['hx_yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('hx_yihexiao');
            $v['weihexiaojine'] = $v['shijitourujine']-$v['hx_yihexiao'];
            $v['shijitourujine']  = round($v['shijitourujine'] ,2);
            $v['hx_yihexiao']  = round($v['hx_yihexiao'] ,2);
            $v['weihexiaojine']  = round($v['weihexiaojine'] ,2);
            $v['cate_name'] = db('cg_ti_cate t')->join('cg_ti t2','t2.cate_id=t.id')->where('t2.id',$v['ti_id'])->value('t.title');
            $v['fb_shijitourufeiyong'] = db('cg_ti_list')->where($where)->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('fb_shijitourufeiyong');
            $list[$k] = $v;
        }

        $data['list'] = $list;
        $this->assign('data',$data);

        //查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);
        return $this->fetch();
    }

    //加载更多核销明细
    public function hexiaomore(){
        $listrows = 10;
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type');
        $where = [];
        switch(intval($type)){
            case 1: //核销中
                $hx_ids = db('cg_ti_hexiao')->where('status',1)->column('id');
                $list_ids = db('cg_ti_hexiao_list')->where('hx_id','in',$hx_ids)->column('list_id');
                $where['id'] = ['in',$list_ids];
                $where['ti_id'] = ['in',$tiids];
                break;
            case 3: //未反馈
                //已反馈
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
                $fb_ids = implode(',',$fb_ids);
                $ti_ids = db('cg_ti')->where(['status'=>7])->column('id');
                $ti_ids = implode(',',$ti_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"not in($fb_ids) and ti_id in($ti_ids) and ti_id in($tiids)"];
                break;
            case 2: //不予核销
            case 4: //未核查
            case 5: //已锁定
                $where['hx_status'] = $type;
                $where['ti_id'] = ['in',$tiids];
                break;
            default: //可核销
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
//                echo db('cg_ti')->getLastSql();
                $fb_ids = implode(',',$fb_ids);
                $tiids = implode(',',$tiids);
                $where['ti_id'] = ['exp',"in($fb_ids) and ti_id in($tiids)"];
                $where['hx_status'] = ['<>',2];
        }
        $page = $this->request->param('page');
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $list = db('cg_ti_list')->where($where)->page($page,$listrows)->select(); //先加载两条
//        echo db('cg_ti_list')->getLastSql();
        foreach($list as $k=>$v){
            if($data['arealat']==2) { //区域纬度选择经销商
                $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
                $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            }
            if($data['productlat']==1) { //品牌
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($data['productlat']==2) { //品类
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($data['productlat']==3) { //系列
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($data['productlat']==4) { //sku
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }else{
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }
            $v['shijitourujine'] = $v['fb_shijitourufeiyong'];
            $v['weihexiaojine'] = $v['shijitourujine']-$v['hx_yihexiao'];
            $v['shenqingren'] = db('employee')->where('id',$v['cuser'])->value('em_name');
            $v['cate_name'] = db('cg_ti_cate t')->join('cg_ti t2','t2.cate_id=t.id')->where('t2.id',$v['ti_id'])->value('t.title');
            $list[$k] = $v;
        }

//查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);

        foreach($list as $k=>$v){
            if($v['start']){
                $v['huodongkaishiriqi'] = $v['start'];
            }else{
                $v['huodongkaishiriqi'] = strtotime($v['year'].'-'.$v['month'].'-'.'1');
            }
            $list[$k] = $v;
        }

        if(intval($type)==1){
            //核销中
            foreach($list as $k=>$v){
                $t = db('cg_ti_hexiao_list')
                    ->where('list_id',$v['id'])
                    ->field('shijitourujine y_shijitourujine,weishuihexiaojine,youwufapiao,fapiaohao,shuilv hx_shuilv,shuijin,isVAT hx_isVAT,hanshuihexiaojine hx_hanshuihexiaojine,shijitourujine hx_shijitourujine,yuebuhexiao,huodongkaishiriqi,beizhu hx_beizhu')
                    ->find();
                $v = array_merge($v,$t);
                $list[$k] = $v;
            }
        }

        foreach($list as $k=>$v){
            $no = $page*$listrows+$k+1;
            $link1 = url('view',['id'=>$data['id']]);
            $title1 = isset($v['net_title'])?'<a href="javascript:;">'.$v['net_title'].'</a>':'无';
            $title2 = isset($v['system_title'])?'<a href="javascript:;">'.$v['system_title'].'</a>':'无';
            $feiyongkemu3 = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $rand = mt_rand();
            $link2 = url('buyuhexiao',['id'=>$v['id']]);
            $start = date('Y-m-d',$v['start']);
            $pmop = '';
            foreach($paymethod as $k1=>$v1){
                $pmop .= '<option value='.$v1['id'].$v['paymethod']==$v1['id']?'selected':''.'>'.$v1['title'].'</option>';
            }
            echo <<<EOF
<tr class="data">
                <td>{$no}</td>
                <td><input type="checkbox" name="items" class="form-control" value="{$v['id']}"></td>
                <td>{$v['shenqingren']}</td>
                <td><a href="{$link1}">{$data['sn']}</a></td>
                <td>{$data['sn']}-{$v['sn']}</td>
                <td>无</td>
                <td>{$title1}</td>
                <td>{$title2}</td>
                <td>{$v['product_name']}</td>
                <td>{$feiyongkemu3}</td>
                <td class="ObjectNum">{$v['shijitourujine']}</td>
                <td class="ObjectNum">{$v['hx_yihexiao']}</td>
                <td class="ObjectNum">{$v['weihexiaojine']}</td>
                <td><input name="weishuihexiaojine" type="text" class="form-control" value="{$v['weihexiaojine']}" style="min-width: 100px;width: 100px"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="1">有
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="0">无
                        </label>
                    </div>
                </td>
                <td><input type="text" name="fapiaohao" class="form-control"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="1">是
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="0" checked>否
                        </label>
                    </div>
                </td>
                <td><input type="text" style="min-width: 60px;width: 60px;" class="form-control" name="shuilv" value="0.00">%</td>
                <td><input type="text" style="min-width: 80px;width: 80px;" class="form-control" name="shuijin" value="0.00"></td>
                <td><input type="text" class="form-control" placeholder="" name="hanshuihexiaojine"  value="{$v['weihexiaojine']}" readonly></td>
                <td><input type="text" class="form-control" placeholder="" name="shijitourujine" value="{$v['weihexiaojine']}"></td>
                <td><input type="checkbox" name="yuebuhexiao" class="form-control" value="1"></td>
                <td><input type="text" class="form-control layer-date" name="huodongkaishiriqi" onclick="laydate()" value="{$start}"></td>
                <td><select name="zhifufangshi"  class="form-control">{$pmop}</select></td>
                <td><input type="text" name="beizhu" class="form-control"></td>
                <td>
                    <button type="button" class="btn-info buyuhexiao" data-link="{$link2}" data-shijitouru="{$v['fb_shijitourufeiyong']}" data-yihexiao="{$v['hx_yihexiao']}">本条不予核销</button>
                </td>
            </tr>
EOF;

        }
    }

    //加载更多核销明细按照整单
    public function hexiaomorebyzd(){
        $listrows = 10;
        $tiids = $this->request->param('tiids');
        $tiids = json_decode($tiids);
        $type = $this->request->param('type');
        $where = [];
        $where['ti_id'] = ['in',$tiids];

        switch($type){
            case 1: //核销中
                $hx_ids = db('cg_ti_hexiao')->where('status',1)->column('id');
                $list_ids = db('cg_ti_hexiao_list')->where('hx_id','in',$hx_ids)->column('list_id');
                $where['id'] = ['in',$list_ids];
                break;
            case 3: //未反馈
                //已反馈
                $fb_ids = db('all_ti_feeback_list')->where(['state'=>3,'type'=>1])->column('apply_id');
                $fb_ids = implode(',',$fb_ids);
                $ti_ids = db('cg_ti')->where(['status'=>7])->column('id');
                $ti_ids = implode(',',$ti_ids);
                $where['ti_id'] = ['exp',"not in($fb_ids) and ti_id in($ti_ids)"];
                break;
            case 2: //不予核销
            case 4: //未核查
            case 5: //已锁定
                $where['hx_status'] = $type;
                break;
            default:
                $where['hx_status'] = 0;
        }

        //查询申请单
        $page = $this->request->param('page');
        $data = db('cg_ti')->where('id','in',$tiids)->find();
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['jxs_sn'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('sn');
        $list = db('cg_ti_list')->where($where)->group('ti_id,paymethod')->page($page,$listrows)->select(); //先加载两条
        //echo db('cg_ti_list')->getLastSql();
        $data['area_title'] = '网点';
        $data['product_title'] = '产品纬度';

        foreach($list as $k=>$v){
            $v['ti_title'] = db('cg_ti')->where('id',$v['ti_id'])->value('title');
            $v['ti_ctime'] = db('cg_ti')->where('id',$v['ti_id'])->value('ctime');
            if($data['arealat']==2) { //区域纬度选择经销商
                //网点个数
                $v['net_num'] = db('cg_ti_list')
                    ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                    ->count('DISTINCT net');
            }
            //费用科目
            $v['feetype'] = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->count('DISTINCT feetype');

            //产品纬度个数
            $temp = db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT brand');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT category');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT series');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT sku');

            $temp += db('cg_ti_list')
                ->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])
                ->value('DISTINCT product');

            $v['product_name'] = $temp;

            $v['shijitourujine'] = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('fb_shijitourufeiyong');
            $v['hx_yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('hx_yihexiao');
            $v['weihexiaojine'] = $v['shijitourujine']-$v['hx_yihexiao'];
            $v['shijitourujine']  = round($v['shijitourujine'] ,2);
            $v['hx_yihexiao']  = round($v['hx_yihexiao'] ,2);
            $v['weihexiaojine']  = round($v['weihexiaojine'] ,2);
            $list[$k] = $v;
        }

        //查询支付方式
        $paymethod = db('cg_paymethod')->field('id,title')->select();
        $this->assign('paymethod',$paymethod);

        foreach($list as $k=>$v){
            $no = $page*$listrows+$k+1;
            $link1 = url('view',['id'=>$data['id']]);
            $title1 = isset($v['net_title'])?'<a href="javascript:;">'.$v['net_title'].'</a>':'无';
            $title2 = isset($v['system_title'])?'<a href="javascript:;">'.$v['system_title'].'</a>':'无';
            $feiyongkemu3 = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $rand = mt_rand();
            $link2 = url('buyuhexiao',['id'=>$v['id']]);
            $link3 = db('cg_ti_list')->where($where)->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['paymethod']])->sum('fb_shijitourufeiyong');
            $pmop = '';
            foreach($paymethod as $k1=>$v1){
                $pmop .= '<option value='.$v1['id'].$v['paymethod']==$v1['id']?'selected':''.'>'.$v1['title'].'</option>';
            }
            $v['shenqingren'] = db('employee')->where('id',$v['cuser'])->value('em_name');
            $ti_time = date('Y-m-d',$v['ti_ctime']);
            echo <<<EOF
<tr class="data">
                <td>{$no}</td>
                <td><input type="checkbox" name="items" class="form-control" value="{$v['ti_id']}"></td>
                <td>{$v['shenqingren']}</td>
                <td><a href="{$link1}">{$data['sn']}</a></td>
                <td>{$v['ti_title']}</td>
                <td>{$v['cate_name']}</td>
                <td>{$ti_time}</td>
                <td>{$v['net_num']}</td>
                <td>{$v['fee_type']}</td>
                <td>{$v['product_name']}</td>
                <td class="ObjectNum">{$v['shijitourujine']}</td>
                <td class="ObjectNum">{$v['hx_yihexiao']}</td>
                <td class="ObjectNum">{$v['weihexiaojine']}</td>
                <td><input name="weishuihexiaojine" type="text" class="form-control" value="{$v['weihexiaojine']}" style="min-width: 100px;width: 100px"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="1">有
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="youwufapiao" name="ionse{$rand}" value="0">无
                        </label>
                    </div>
                </td>
                <td><input type="text" name="fapiaohao" class="form-control"></td>
                <td>
                    <div class="form-group radioDiv">
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="1">是
                        </label>
                        <label class="radio-inline">
                            <input type="radio" class="shizengzhishui" name="isVAT{$rand}" value="0" checked>否
                        </label>
                    </div>
                </td>
                <td><input type="text" style="min-width: 60px;width: 60px;" class="form-control" name="shuilv" value="0.00">%</td>
                <td><input type="text" style="min-width: 80px;width: 80px;" class="form-control" name="shuijin" value="0.00"></td>
                <td><input type="text" class="form-control" placeholder="" name="hanshuihexiaojine"  value="{$v['weihexiaojine']}" readonly></td>
                <td><input type="text" class="form-control" placeholder="" name="shijitourujine" value="{$v['weihexiaojine']}"></td>
                <td><input type="checkbox" name="yuebuhexiao" class="form-control" value="1"></td>
                <td><select name="zhifufangshi"  class="form-control">{$pmop}</select></td>
                <td><input type="text" name="beizhu" class="form-control"></td>
                <td>
                    <button type="button" class="btn-info buyuhexiao" data-link="{$link2}" data-shijitouru="{$link3}" data-yihexiao="{$v['hx_yihexiao']}">本条不予核销</button>
                </td>
            </tr>
EOF;

        }
    }

    //更换经销商
    public function changejxs(){
        //查询所有经销商
        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $this->assign([
            'sn'=>$sn,
            'title'=>$title,
        ]);
        $where = [];
        $where['stuff'] = ['like','%'.session('employee_id').'%'];
        if($sn){
            $where['sn'] = ['like','%'.$sn.'%'];
        }
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        $data = db('cg_jxs')->field('id,sn,title')
            ->where($where)
            ->select();
        //echo db('cg_jxs')->getLastSql();
        $sum1 = 0;
        $sum2 = 0;
        $sum3 = 0;
        $sum4 = 0;
        $sum5 = 0;
        $sum6 = 0;
        foreach($data as $k=>$v){
            $v['yipizhun'] = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->join('cg_ti_list t3','t3.ti_id=t2.id')
                ->where(['t2.jxs_id'=>$v['id'],'t.state'=>'3'])
                ->sum('t3.fb_shijitourufeiyong'); //已批准--反馈的批准含税金额
            $sum1 += $v['yipizhun'];
            $v['yipizhun'] = round($v['yipizhun'],2);

            $v['yihexiao'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->where(['t.jxs_id'=>$v['id'],'t.status'=>2])
                ->sum('hanshuihexiaojine'); //已核销--已批准的核销含税金额
            $sum2 += $v['yihexiao'];
            $v['yihexiao'] = round($v['yihexiao'],2);

            //未核销
            $v['shenqingzhong'] = db('cg_ti_hexiao t')
                ->where(['t.status'=>1,'t.jxs_id'=>$v['id']])
                ->sum('t.tax');//申请中--已提交工作流
            $sum3 += $v['shenqingzhong'];
            $v['shenqingzhong'] = round($v['shenqingzhong'],2);

            //未申请
            $v['weishenqing'] = db('cg_ti_hexiao t')
                ->where(['t.status'=>0,'t.jxs_id'=>$v['id']])
                ->sum('t.notax');//未申请--生成了核销申请单-已存为草稿-但未提交工作流
            $sum4 += $v['weishenqing'];
            $v['weishenqing'] = round($v['weishenqing'],2);

            //不予核销
            $v['buyuhexiao'] = db('cg_ti_list t')
                ->join('cg_ti t2','t.ti_id=t2.id')
                ->where(['t.hx_status'=>2,'t2.jxs_id'=>$v['id']])
                ->sum('t.hx_yihexiao2');//已核销含税
            $fb_shijitourufeiyong = db('cg_ti_list t')
                ->join('cg_ti t2','t.ti_id=t2.id')
                ->where(['t.hx_status'=>2,'t2.jxs_id'=>$v['id']])
                ->sum('t.fb_shijitourufeiyong');//实际投入金额含税
            $v['buyuhexiao'] = $fb_shijitourufeiyong-$v['buyuhexiao'];
            $sum5 += $v['buyuhexiao'];
            $v['buyuhexiao'] = round($v['buyuhexiao'],2);

            //可以核销
            $v['kehexiao'] = $v['yipizhun']-$v['yihexiao']-$v['shenqingzhong']- $v['weishenqing'] -$v['buyuhexiao'];
            $sum6 += $v['kehexiao'];
            $v['kehexiao'] = round($v['kehexiao'],2);


            $data[$k] = $v;
        }
        $sum1 = round($sum1,2);
        $sum2 = round($sum2,2);
        $sum3 = round($sum3,2);
        $sum4 = round($sum4,2);
        $sum5 = round($sum5,2);
        $sum6 = round($sum6,2);
        $this->assign([
            'data'=>$data,
            'sum1'=>$sum1,
            'sum2'=>$sum2,
            'sum3'=>$sum3,
            'sum4'=>$sum4,
            'sum5'=>$sum5,
            'sum6'=>$sum6,
        ]);
//        dump($data);

        return $this->fetch();
    }

    //更换经销商后
    public function changejxsafter(){
        $id = $this->request->param('id');//经销商id
        $data = db('cg_jxs')->where('id',$id)->find();

        $showtype = $this->request->get('showtype');//显示类型
        $w = [];
        $w['jxs_id'] = $id;
        if($showtype==1){  //只显示可核销的
            $w['hx_status']=['exp','is null or hx_status=0'];
        }

        $list = db('cg_ti')->where($w)->select();
        //echo db('cg_ti')->getLastSql();
        $sum1 = 0;
        $sum2 = 0;
        $sum3 = 0;
        $sum4 = 0;
        $sum5 = 0;

        foreach($list as $k=>$v){
            $v['cuser_name'] = db('employee')->where('id',$v['cuser'])->value('em_name');
            $v['yipizhun'] = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->join('cg_ti_list t3','t3.ti_id=t2.id')
                ->where(['t2.id'=>$v['id'],'t.state'=>'3'])
                ->sum('t3.fb_shijitourufeiyong'); //已批准--反馈的批准含税金额
            $v['yipizhun'] = round( $v['yipizhun'],2);

            $listids = db('cg_ti_list')->where('ti_id',$v['id'])->column('id');//按照ti_id查询listid
            $listids = implode(',',$listids);
            $hexids = db('cg_ti_hexiao')->where(['status'=>2,'jxs_id'=>$id])->column('id');//按照审核状态和jxs_id查hx_id
            $hexids = implode(',',$hexids);
            $v['yihexiao'] = db('cg_ti_hexiao_list')
                ->where(['list_id'=>['in',$listids],'hx_id'=>['in',$hexids]]) //组合查询条件
                ->sum('weishuihexiaojine'); //已核销--
            $v['yihexiao'] = round( $v['yihexiao'],2);

            //未核销
            $v['shenqingzhong'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where(['t.status'=>1,'t3.ti_id'=>$v['id']])
                ->sum('t.tax');//申请中--已提交工作流
            $v['shenqingzhong'] = round( $v['shenqingzhong'],2);


            //未申请
            $v['weishenqing'] = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where(['t.status'=>0,'t3.ti_id'=>$v['id']])
                ->sum('t.tax');//未申请--生成了核销申请单-已存为草稿-但未提交工作流
            $v['weishenqing'] = round( $v['weishenqing'],2);


            //不予核销
            $fb_shijitourufeiyong = db('cg_ti_list t')
                ->where(['t.hx_status'=>2,'ti_id'=>$v['id']])
                ->sum('t.fb_shijitourufeiyong');//实际投入金额含税

            $v['buyuhexiao'] = $fb_shijitourufeiyong;
            $v['buyuhexiao'] = round( $v['buyuhexiao'],2);


            //可以核销
            $v['kehexiao'] = $v['yipizhun']-$v['yihexiao'];
            $v['kehexiao'] = round( $v['kehexiao'],2);

            if($showtype==1){
                if($v['kehexiao']==0){
                    unset($list[$k]);
                }else{
                    $sum1 += $v['yipizhun'];
                    $sum2 += $v['yihexiao'];
                    $sum3 += $v['shenqingzhong'];
                    $sum4 += $v['weishenqing'];
                    $sum5 += $v['kehexiao'];
                    $list[$k] = $v;
                }
            }else{
                $sum1 += $v['yipizhun'];
                $sum2 += $v['yihexiao'];
                $sum3 += $v['shenqingzhong'];
                $sum4 += $v['weishenqing'];
                $sum5 += $v['kehexiao'];
                $list[$k] = $v;
            }
        }
        $sum1 = round($sum1,2);
        $sum2 = round($sum2,2);
        $sum3 = round($sum3,2);
        $sum4 = round($sum4,2);
        $sum5 = round($sum5,2);
        $data['list'] = $list;
        $this->assign('data',$data);
        $this->assign([
            'data'=>$data,
            'sum1'=>$sum1,
            'sum2'=>$sum2,
            'sum3'=>$sum3,
            'sum4'=>$sum4,
            'sum5'=>$sum5,
        ]);
        return $this->fetch();
    }

    //设置发票信息
    public function setInvoice(){
        return $this->fetch();
    }

    //设置本条不予核销
    public function buyuhexiao(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti_list')->where(array('id'=>$id))->update(['hx_status'=>2]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"操作成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"操作失败"
            ]);die;
        }
    }

    //生成核销预览--按照明细
    public function makehxpreview(){

        $notax = $this->request->post('notax');
        if(!$notax){
            echo json_encode([
                'success'=>false,
                'msg'=>'未税核销总额不能为空',
            ]);die;
        }
        $tax = $this->request->post('tax');
        if(!$tax){
            echo json_encode([
                'success'=>false,
                'msg'=>'含税核销总额不能为空',
            ]);die;
        }
        $shuijinheji = $this->request->post('shuijinheji');
        if($shuijinheji==''){
            echo json_encode([
                'success'=>false,
                'msg'=>'税金合计不能为空',
            ]);die;
        }
        $data = $this->request->post('data/a');
        foreach($data as $k=>$v){

            $valid = new Valid([
               'weishuihexiaojine|未税核销金额'=>'require|number',
               'youwufapiao|有无发票'=>'require',
               'fapiaohao|发票号'=>'require',
               'shizengzhishui|是否增值税'=>'require',
               'shuilv|税率'=>'require|number',
               'shuijin|税金'=>'require|number',
               'hanshuihexiaojine|含税核销金额'=>'require|number',
               'shijitourujine|实际投入金额'=>'require|number',
//                   'yuebuhexiao|余额不予核销'=>'require',
               'huodongkaishiriqi|活动开始日期'=>'require|dateFormat=Y-m-d',
               'zhifufangshi|支付方式'=>'require',
               'beizhu|备注'=>'require',
            ]);
            if($valid->check($v)){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$valid->getError()
                ]);die;
            }

            $data[$k]['huodongkaishiriqi'] = strtotime($v['huodongkaishiriqi']);
            $data[$k]['cuser'] = session('employee_id');
            $data[$k]['puser'] = session('employee_id');
            $data[$k]['ctime'] = time();
            $data[$k]['ptime'] = time();
            $data[$k]['ti_id'] = $v['ti_id'];
            $data[$k]['sn'] = $k+1;
        }

        //查询jxs_id
        $jxs_id = db('cg_ti')->where('id',$data[0]['ti_id'])->value('jxs_id');

        $hx_sn = $this->producehxSN(); //生成核销sn
        //插入核销主表
        db('cg_ti_hexiao')->insert([
            'cuser'=>session('employee_id'),
            'puser'=>session('employee_id'),
            'ctime'=>time(),
            'ptime'=>time(),
            'notax'=>$notax,
            'tax'=>$tax,
            'jxs_id'=>$jxs_id,
            'shuijinheji'=>$shuijinheji,
            'sn'=>$hx_sn,
        ]);
        $hx_id = db('cg_ti_hexiao')->getLastInsID();

        //附上hx_id
        foreach($data as $k=>$v){
            $data[$k]['hx_id'] = $hx_id;
        }

        //插入明细
        $bool = db('cg_ti_hexiao_list')->insertAll($data);

        //更新原明细，如果余额不核销，改变状态；扣除核销的余额
        foreach($data as $k=>$v){
            db('cg_ti_list')
                ->where('id',$v['list_id'])
                ->setInc('hx_yihexiao',$v['weishuihexiaojine']);
            if($v['yuebuhexiao']){
                db('cg_ti_list')
                    ->where('id',$v['list_id'])
                    ->update(['hx_status'=>2]);
            }
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok','hx_id'=>$hx_id]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }

    }

    //生成核销预览--按照整单
    public function makehxpreviewbyzd(){

        $notax = $this->request->post('notax');
        if(!$notax){
            echo json_encode([
                'success'=>false,
                'msg'=>'未税核销总额不能为空',
            ]);die;
        }
        $tax = $this->request->post('tax');
        if(!$tax){
            echo json_encode([
                'success'=>false,
                'msg'=>'含税核销总额不能为空',
            ]);die;
        }
        $shuijinheji = $this->request->post('shuijinheji');
        if($shuijinheji==''){
            echo json_encode([
                'success'=>false,
                'msg'=>'税金合计不能为空',
            ]);die;
        }
        $data = $this->request->post('data/a');
        foreach($data as $k=>$v){

            $valid = new Valid([
               'weishuihexiaojine|未税核销金额'=>'require|number',
               'youwufapiao|有无发票'=>'require',
               'fapiaohao|发票号'=>'require',
               'shizengzhishui|是否增值税'=>'require',
               'shuilv|税率'=>'require|number',
               'shuijin|税金'=>'require|number',
               'hanshuihexiaojine|含税核销金额'=>'require|number',
               'shijitourujine|实际投入金额'=>'require|number',
//                   'yuebuhexiao|余额不予核销'=>'require',
               'zhifufangshi|支付方式'=>'require',
               'beizhu|备注'=>'require',
            ]);
            if($valid->check($v)){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$valid->getError()
                ]);die;
            }

        }

        //拆分每项
        $insert = [];
        foreach($data as $k=>$v){

            $tiaomushu = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['zhifufangshi']])->count();
//            echo db('cg_ti')->getLastSql();die;
            $a1 = round($v['weishuihexiaojine']/$tiaomushu,2);
            $a2 = round($v['shuijin']/$tiaomushu,2);
            $a3 = round($v['hanshuihexiaojine']/$tiaomushu,2);
            $a4 = round($v['shijitourujine']/$tiaomushu,2);


            $column = db('cg_ti_list')->where(['ti_id'=>$v['ti_id'],'paymethod'=>$v['zhifufangshi']])->column('id');
            foreach($column as $k1=>$v1){
                $temp = [];
                $temp['list_id'] = $v1;
                $temp['weishuihexiaojine'] = $a1;
                $temp['shuijin'] = $a2;
                $temp['hanshuihexiaojine'] = $a3;
                $temp['shijitourujine'] = $a4;
                $temp['yuebuhexiao'] = $v['yuebuhexiao'];
                $temp['zhifufangshi'] = $v['zhifufangshi'];
                $temp['cuser'] = session('employee_id');
                $temp['puser'] = session('employee_id');
                $temp['ctime'] = time();
                $temp['ptime'] = time();
                $temp['ti_id'] = $v['ti_id'];
                $temp['sn'] = $k+1+$k1;
                $insert[] = $temp;
            }
        }


        //查询jxs_id
        $jxs_id = db('cg_ti')->where('id',$data[0]['ti_id'])->value('jxs_id');

        $hx_sn = $this->producehxSN(); //生成核销sn
        //插入核销主表
        db('cg_ti_hexiao')->insert([
            'cuser'=>session('employee_id'),
            'puser'=>session('employee_id'),
            'ctime'=>time(),
            'ptime'=>time(),
            'notax'=>$notax,
            'tax'=>$tax,
            'jxs_id'=>$jxs_id,
            'shuijinheji'=>$shuijinheji,
            'sn'=>$hx_sn,
        ]);
        $hx_id = db('cg_ti_hexiao')->getLastInsID();

        //附上hx_id
        foreach($insert as $k=>$v){
            $insert[$k]['hx_id'] = $hx_id;
        }

        //插入明细
        $bool = db('cg_ti_hexiao_list')->insertAll($insert);

        //更新原明细，如果余额不核销，改变状态；扣除核销的余额
        foreach($insert as $k=>$v){
            db('cg_ti_list')
                ->where('id',$v['list_id'])
                ->setInc('hx_yihexiao',$v['weishuihexiaojine']);
            if($v['yuebuhexiao']){
                db('cg_ti_list')
                    ->where('id',$v['list_id'])
                    ->update(['hx_status'=>2]);
            }
        }

        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok','hx_id'=>$hx_id]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }

    }

    //核销预览
    public function hxpreview(){

        $hx_id = $this->request->param('hx_id');

        if($_POST){
            $savetype = $this->request->param('savetype');
            $data = [];
            $data['beizhu'] = $this->request->post('beizhu');
            $data['guidangtixing'] = $this->request->post('guidangtixing');
            if($savetype=='save2'){
                $data['status'] = 3; //提交工作流
            }
            $bool = db('cg_ti_hexiao')->where('id',$hx_id)->update($data);
            if(false!==$bool){
                $this->updateAttach3($hx_id);
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $basic = db('cg_ti_hexiao')->where('id',$hx_id)->find();
        $basic['jxs_title'] = db('cg_jxs')->where('id',$basic['jxs_id'])->value('title');
        $basic['cuser_title'] = db('employee')->where('id',$basic['cuser'])->value('em_name');

        $basic['area_title'] = '网点名称';
        $basic['area_title2'] = '系统名称';

        $basic['product_title'] = '产品纬度';



            $this->assign('basic',$basic);

        $data = db('cg_ti_hexiao_list t')
            ->join('cg_ti_list t2','t.list_id=t2.id')
            ->join('cg_ti t3','t2.ti_id=t3.id')
            ->where('t.hx_id',$hx_id)
            ->field('t.*,t2.sn list_sn,t2.ti_id,t2.feetype,t2.net_id,t2.brand,t2.category,t2.series,t2.sku,t2.product,t2.id list_id,t2.hx_yihexiao,t2.fb_shijiweishui,t2.hx_yihexiao,t2.start,t3.arealat,t3.productlat,t3.sn ti_sn,t3.cuser ti_cuser')->select();
//        echo db('cg_ti')->getLastsql();
        foreach($data as $k=>$v){
            $v['cuser_title'] = db('employee')->where('id',$v['cuser'])->value('em_name');
            $v['cuser_dep'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$v['cuser'])->value('t.de_name');

            $v['ti_cuser'] = db('employee')->where('id',$v['ti_cuser'])->value('em_name');

            if($v['arealat']==2) { //区域纬度选择经销商
                $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
                $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            }

            if($v['productlat']==1) { //品牌
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            }elseif($v['productlat']==2) { //品类
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            }elseif($v['productlat']==3) { //系列
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            }elseif($v['productlat']==4) { //sku
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            }else{
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            }


            $v['weihexiaojine'] = $v['fb_shijiweishui']-$v['hx_yihexiao'];
//            $v['zhifufangshi'] = db('cg_paymethod')->where('id',$v['zhifufangshi'])->value('title');
            $data[$k] = $v;
        }

        //实际投入金额合计
        $sum_shijitourujine = $this->array_sum($data,'shijitourujine');
        $sum_hx_yihexiao = $this->array_sum($data,'hx_yihexiao');
        $sum_weihexiaojine = $this->array_sum($data,'weihexiaojine');
        $sum_weishuihexiaojine = $this->array_sum($data,'weishuihexiaojine');
        $sum_shuijin = $this->array_sum($data,'shuijin');
        $sum_hanshuihexiaojine = $this->array_sum($data,'hanshuihexiaojine');

        $this->assign('data',$data);
        $this->assign('sum_shijitourujine',$sum_shijitourujine);
        $this->assign('sum_hx_yihexiao',$sum_hx_yihexiao);
        $this->assign('sum_weihexiaojine',$sum_weihexiaojine);
        $this->assign('sum_weishuihexiaojine',$sum_weishuihexiaojine);
        $this->assign('sum_shuijin',$sum_shuijin);
        $this->assign('sum_hanshuihexiaojine',$sum_hanshuihexiaojine);
        $this->assign('sum_shijitourujine',$sum_shijitourujine);


        //查询附件
        if($basic['attach']){
            $attach = unserialize($basic['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
            $this->assign('attach',$attach);
        }
        return $this->fetch();
    }

    //返回二维数组中的某二维key的合计
    public function array_sum($arr,$key){
        $sum = 0;
        foreach($arr as $k=>$v){
            $sum += $v[$key];
        }
        return $sum;
    }

    //查看流程图
    public function workflowchart(){
        $id = $this->request->param('id');
         $cate_id=db("cg_ti")->where(["id"=>$id])->value("cate_id");
        if($cate_id==1){
            $ywid=2;
        }else if($cate_id==2){
            $ywid=21;
        }else
            $ywid=22;
        $workId = db('cg_workflow')->where(['ywlx'=>$ywid,'yw_id'=>$id])->value('workId');
        $trackId = db('cg_workflow')->where(['ywlx'=>$ywid,'yw_id'=>$id])->value('trackId');
        header('location:'.config('workflow_url').'/workflow/module/workflow/flow.info.html?workId='.$workId.
            '&trackId='.$trackId);
    }
}
